如何在TypeScript中从接口值类型提取联合类型?
实现提取接口值类型联合的ValueType类型转换器
你可以通过泛型+keyof索引访问类型来实现这个ValueType,具体写法如下:
type ValueType<T> = T[keyof T];
验证示例
用你给出的Dog接口测试:
interface Dog { name: string; birth: number; } // 直接传入接口类型,得到值类型的联合 type DogProperties = ValueType<Dog>; // 类型为 string | number
如果你的场景是从变量的类型中提取(比如你例子里的typeof dog),只要变量符合目标接口结构,同样适用:
const dog: Dog = { name: "旺财", birth: 2020 }; type DogPropertiesFromVar = ValueType<typeof dog>; // 结果仍是 string | number
原理说明
keyof T会提取出类型T的所有键名组成的联合类型,比如keyof Dog就是"name" | "birth"T[keyof T]是索引访问类型,表示取T中所有键对应的类型,这些类型会自动合并成联合类型
内容的提问来源于stack exchange,提问作者Mathieu CAROFF
相关产品推荐
相关产品推荐

