简体   繁体   English

我如何转换 TypeScript 类型?

[英]How I can convert TypeScript type?

I have the code我有代码

interface IProps {
  name: string;
  age: number;
}

I want to get我想得到

type Result = {
  key: 'name',
  value: string
} | {
  key: 'age',
  value: number
}

Is there any good way?有什么好办法吗?

COnsider this example:考虑这个例子:

interface IProps {
    name: string;
    age: number;
}

type Distribute<Obj, Keys extends keyof Obj> = Keys extends any ? { key: Keys, value: Obj[Keys] } : never

type Builder<T> = Distribute<T, keyof T>

// type Result = {
//     key: "name";
//     value: string;
// } | {
//     key: "age";
//     value: number;
// }
type Result = Builder<IProps>

Playground操场

Here you can find more information about distributivity 在这里您可以找到有关分配的更多信息

This line of code { key: Keys, value: Obj[Keys] } is applied to each IProps key separately because of distributivity这行代码{ key: Keys, value: Obj[Keys] }由于分布性,分别应用于每个IProps

PS There is also an alternative way: PS还有一种替代方法:

type AlternativeWay<T> = {
    [Prop in keyof T]: {
        key: Prop,
        value: T[Prop]
    }
}[keyof T]


type Result = AlternativeWay<IProps>

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

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