且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 TypeScript 中将一种泛型类型的结构复制到另一种泛型?

更新时间:2022-12-17 16:05:45

我想你只是想要一个映射类型,将每个属性的类型设置为布尔值?

I think you just want a mapped type that sets the type of each property to boolean?

type GenericMap<T> = {
    [K in keyof T]: boolean
}

你会使用哪个:

interface Input {
    name: string;
    heightCm: number;
    dob: Date;
}

type Output = GenericMap<Input>
// Output is
// {
//    name: boolean;
//    heightCm: boolean;
//    dob: boolean;
// }

游乐场

作为(潜在的)改进,您甚至可以检查此类型别名中的 string 并返回 truefalse,而不是 布尔值.

As a (potential) improvement, you could even check for string in this type alias and return true or false, rather than boolean.

type GenericMap<T> = {
    [K in keyof T]: T[K] extends string ? true : false
}

哪个会产生这种类型:

type Output = GenericMap<Input>
// {
//    name: true;
//    heightCm: false;
//    dob: false;
// }