如何在 TypeScript 中将一种泛型类型的结构复制到另一种泛型? [英] How to copy the structure of one generic type to another generic in TypeScript?

查看:50
本文介绍了如何在 TypeScript 中将一种泛型类型的结构复制到另一种泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下输入类型:

Imagine we have the following input type:

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

我想写一个函数,可以根据这个输入产生以下输出类型:

I would like to write a function that can produce the following output type based on this input:

interface Output {
    name: boolean;
    heightCm: boolean;
    dob: boolean;
}

换句话说,一个函数复制输入的结构并将该结构作为输出返回,将所有值设置为布尔值.

In other words, a function that copies the structure of input and returns that structure as output, setting all values as booleans.

函数签名看起来像这样:

The function signature would look something like this:

interface GenericMap<T> {
    [key: string]: T;
}

type InputToOutput<In, Out extends GenericMap<boolean>> = (input: In) => Out;

如果 Input 属性的类型最初是字符串,则将该属性标记为 true,否则标记为 false.

If the type of the Input property was originally a string, mark that property as true, otherwise mark as false.

例如该函数将根据上面的 Input 产生以下结果:

E.g. the function would produce the following result based on Input above:

{
    name: true,
    heightCm: false,
    dob: false
}

但最重要的是,它需要是类型安全的,这样我才能在结果对象上接收智能感知.

But most importantly, it needs to be type-safe, such that I can receive intellisense on the resulting object.

非常感谢帮助!

推荐答案

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

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;
// }

这篇关于如何在 TypeScript 中将一种泛型类型的结构复制到另一种泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆