Typescript 如何在将值限制为已知集的同时推断映射的类型?
我正在尝试创建从一组字符串键到一组特定字符串的映射:Typescript 如何在将值限制为已知集的同时推断映射的类型?,typescript,type-inference,Typescript,Type Inference,我正在尝试创建从一组字符串键到一组特定字符串的映射: type Datum = { LOCATION: string, GENDER: number } export const fieldKeys: Record<strings, keyof Datum> = { country: "LOCATION", gender: "GENDER" }; 但是,由于字段键记录键是任意字符串,而不是一组众所周知的属性,因此允许误用: // Passes type checker b
type Datum = { LOCATION: string, GENDER: number }
export const fieldKeys: Record<strings, keyof Datum> = {
country: "LOCATION",
gender: "GENDER"
};
但是,由于字段键
记录键是任意字符串,而不是一组众所周知的属性,因此允许误用:
// Passes type checker but is a bug.
const bug = d[fieldKeys.doesNotExist]
此外,当通过字段键访问时,属性的推断类型是所有可能的数据属性值的并集类型:
// Inferred type is 'string | number' instead of string.
const shouldBeString = d[fieldKeys.country]
理想情况下,TypeScript应该推断记录的键,但这样的代码是不允许的,因为它是递归的:
export const fieldKeys: Record<keyof (typeof fieldKeys), keyof Datum> = {
country: "LOCATION",
gender: "GENDER"
};
有人知道怎么做吗?你能解释一下你想做什么吗?键
国家
和字符串位置
如何连接?为什么它不允许任意字符串?@ritaj我试图扩展描述。现在更清楚了吗?所有这些片段似乎都有效,所以我不确定我是否理解这个问题:我更新了描述,希望能让问题更清楚。
export const fieldKeys: Record<keyof (typeof fieldKeys), keyof Datum> = {
country: "LOCATION",
gender: "GENDER"
};
const keyOf = <D, K extends keyof D>(k: K): K => k
export const fieldKeys = {
country: keyOf<Datum, "LOCATION">("LOCATION"),
gender: keyOf<Datum, "GENDER">("GENDER")
} as const;
type Datum = { LOCATION: string, GENDER: number }
export const fieldKeys = {
country: "LOCATION",
gender: "GENDER",
// Requirement: Type checker complains that NODATUMPROPERTY is is not a property of Datum.
noDatumProperty: "NODATUMPROPERTY"
};
const d: Datum = { LOCATION: "Germany", GENDER: 1 }
// Requirement: inferred type is 'string'
const country = d[fieldKeys.country]
// Requirement: Type checker complains about non-existing property in fieldKeys.
const bug1 = d[fieldKeys.doesNotExist]