问题描述
限时送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
并返回 true
或 false
,而不是 <代码>布尔值.
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:关键词]
发布评论