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

编程入门 行业动态 更新时间:2024-10-27 06:22:19
本文介绍了如何在 TypeScript 中将一种泛型类型的结构复制到另一种泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 09:34:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1187572.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   类型   结构   如何在   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!