[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
string
s or allnumber
s, 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
}
分类:
TypeScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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"