从打字稿中的任何接口自动创建布尔类型
Automatically create a boolean type from any interface in typescript
我有这个示例界面:
interface Input {
api_method: string;
ip: string;
utc_millis: number;
user_agent: string;
rr_sets: {
name: string;
rr_type: string;
ttl: number;
value: string;
}[];
}
并希望从中自动创建此界面:
interface Output {
api_method: boolean;
ip: boolean;
utc_millis: boolean;
user_agent: boolean;
rr_sets: {
name: boolean;
rr_type: boolean;
ttl: boolean;
value: boolean;
}[];
}
从文档 Here 我发现:
type Output= {
[Key in keyof Input]: boolean;
};
将创建此类型:
type Output = {
api_method: boolean;
ip: boolean;
utc_millis: boolean;
user_agent: boolean;
rr_sets: boolean;
}
如何处理任何嵌套 type/interface?
您可以在映射类型中使用条件:
interface Input {
api_method: string;
ip: string;
utc_millis: number;
user_agent: string;
rr_sets: {
name: string;
rr_type: string;
ttl: number;
value: string;
}[];
}
type AllBoolean<T> = {
[K in keyof T]: T[K] extends Array<infer U> ? AllBoolean<U>[] : boolean
}
type Output = AllBoolean<Input>
const output_test: Output = {
api_method: true,
ip: true,
utc_millis: false,
user_agent: true,
rr_sets: [{
name: true,
rr_type: true,
ttl: false,
value: true,
}]
}
我有这个示例界面:
interface Input {
api_method: string;
ip: string;
utc_millis: number;
user_agent: string;
rr_sets: {
name: string;
rr_type: string;
ttl: number;
value: string;
}[];
}
并希望从中自动创建此界面:
interface Output {
api_method: boolean;
ip: boolean;
utc_millis: boolean;
user_agent: boolean;
rr_sets: {
name: boolean;
rr_type: boolean;
ttl: boolean;
value: boolean;
}[];
}
从文档 Here 我发现:
type Output= {
[Key in keyof Input]: boolean;
};
将创建此类型:
type Output = {
api_method: boolean;
ip: boolean;
utc_millis: boolean;
user_agent: boolean;
rr_sets: boolean;
}
如何处理任何嵌套 type/interface?
您可以在映射类型中使用条件:
interface Input {
api_method: string;
ip: string;
utc_millis: number;
user_agent: string;
rr_sets: {
name: string;
rr_type: string;
ttl: number;
value: string;
}[];
}
type AllBoolean<T> = {
[K in keyof T]: T[K] extends Array<infer U> ? AllBoolean<U>[] : boolean
}
type Output = AllBoolean<Input>
const output_test: Output = {
api_method: true,
ip: true,
utc_millis: false,
user_agent: true,
rr_sets: [{
name: true,
rr_type: true,
ttl: false,
value: true,
}]
}