簡體   English   中英

從 typescript 中的任何接口自動創建 boolean 類型

[英]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; 
}

任何嵌套類型/接口將如何完成?

您可以在映射類型中使用條件:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM