简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM