简体   繁体   English

从 typescript 中的任何接口自动创建 boolean 类型

[英]Automatically create a boolean type from any interface in typescript

I have this example 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;
    }[];
}

and want to automatically create this interface from it:并希望从中自动创建此接口:

interface Output {
    api_method: boolean;
    ip: boolean;
    utc_millis: boolean;
    user_agent: boolean;
    rr_sets: {
        name: boolean;
        rr_type: boolean;
        ttl: boolean;
        value: boolean;
    }[];
}

From the documentation Here i found out that this:从文档Here我发现:

type Output= {
    [Key in keyof Input]: boolean;
};

will create this type:将创建这种类型:

type Output = {
    api_method: boolean;
    ip: boolean;
    utc_millis: boolean;
    user_agent: boolean;
    rr_sets: boolean; 
}

How would that be done with any nested type/interface?任何嵌套类型/接口将如何完成?

You can use a conditional in your mapped type:您可以在映射类型中使用条件:

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,
  }]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个通用的 TypeScript 接口,该接口匹配任何类型/接口/对象,但其中的值类型有限制? - How to create a generic TypeScript interface which matches any type/interface/object with restrictions on types for values inside it? 以编程方式从界面创建打字稿用户定义的类型防护 - Programatically Create Typescript User Defined Type Guards from Interface 在 typescript 中使用接口而不是“任何”类型 - Use of interface instead of 'any' type in typescript Typescript 创建一个类型,其属性是接口的属性 - Typescript Create a type whose properties are the properties of an interface 是否可以从任何“n”个定义的接口扩展并在 TypeScript 中创建一个新的子接口? - Is it possible to extend from any of 'n' defined interfaces and create a new child interface in TypeScript? 从 Typescript 中的接口提取方法类型 - Extract method type from an interface in Typescript 是否可以从 TypeScript 接口创建“空” object 接口? - Is it possible to create an “empty” object from a TypeScript interface? 是否可以从 typescript 接口创建等效的 joi? - is it possible to create a joi equivalent from typescript interface? 使用 Typescript 进行接口类型检查 - Interface type check with Typescript 从类型名称创建打字稿类型 - Create typescript type from type name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM