[TypeScript] Mapped Type

Index Signature

type Fruit = {
  name: string
  color: string
  mass: number
}
 
type Dict<T> = { [k: string]: T } // <- index signature
 
const fruitCatalog: Dict<Fruit> = {}
fruitCatalog.apple // Fruit

Using index signature, we will get any key, basicly:

fruitCatalog.apple // Fruit
fruitCatalog.car   // Fruit
fruitCatalog.house // Fruit

 

We want to imporve the type, so that we can limit what key we want to use:

type Fruit = {
  name: string
  color: string
  mass: number
}

type MyFruit = {[FruitKey in "apple" | "cherry"]: Fruit}

function printFruitCatalog(fruitCatalog: MyFruit) {
  fruitCatalog.cherry
  fruitCatalog.apple
  fruitCatalog.pineapple // ERROR: roperty 'pineapple' does not exist on type 'MyFruit'.
}

 

  • in keyword is the maped type.
  • Index signatures can be on all strings or all numbers, but not some subset of strings or numbers.

Notice: 

the following syntax is wrong:

type MyRecord = { [key: "apple" | "cherry"]: Fruit }  // Wrong
type MyRecord = { [key in "apple" | "cherry"]: Fruit } // Correct

 


 

Record

Now we want to make a more gemeralized type based on MyFruit:

type MyFruit = {[FruitKey in "apple" | "cherry"]: Fruit}
type MyRecord<KeyType extends string, ValueType> = {[Key in KeyType]: ValueType}

function printFruitCatalog(fruitCatalog: MyRecord<"apple" | "cherry", Fruit>) {
  fruitCatalog.cherry
  fruitCatalog.apple

  fruitCatalog.pineapple // ERROR
}

 

posted @   Zhentiw  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-08-17 [Machine Learning] Octave Computing on Data
2020-08-17 [Machine Learning] Octave Moving data around
2020-08-17 [Machine Learning] Octave Basic Operations
2018-08-17 [React] Build a slide deck with mdx-deck using Markdown + React
2018-08-17 [React] Spread Component Props in JSX with React
2017-08-17 [React] Create component variations in React with styled-components and "extend"
2017-08-17 [React] Animate your user interface in React with styled-components and "keyframes"
点击右上角即可分享
微信分享提示