繁体   English   中英

[Typescript]:是否可以使用泛型 X 的键和泛型 X 的值创建类型安全映射?

[英][Typescript]: Is it possible to create typesafe Map with key of generic X and value of generic X?

期望的行为是:

const obj: ??? = {
  [Fruit<T>]: Taste<T>,
  [Fruit<Y>]: Taste<Y>,
}

const key: Fruit<T> = ...;

obj[key] // can only be Taste<T>

我知道我可以使用Record<Fruit<T>, Taste<T>>但它仍然允许我为Fruit<Y>设置Taste<T> Fruit<Y>

这样做的一种方法是拥有一个映射类型来表示Fruit与哪种Taste相关联,例如

type FruitTasteMap = {
    apple: 'yummy'
    banana: 'not so much'
}

然后您的对象将被键入为

type F = {
    [k in keyof FruitTasteMap]: FruitTasteMap[k]
} 

这会导致您正在寻找的内容

const ok: F = { // OK
  apple: 'yummy',
  banana: 'not so much'
}

const wrong: F = {
  apple: 'yummy',
  banana: 'like it!' // Type '"like it!"' is not assignable to type '"not so much"'
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM