简体   繁体   中英

TypeScript - Using Generics to Create a Custom Type

I'm using an intermediary step for creating a type that has property keys that must be the same as the keys of a specified interface

// 1. Create Interface
interface IDetail {
    name: string;
    enabled: boolean;
}

// 2. Create a 'type' that has properties that match the properties of an interface
type DetailType = {
    [key in keyof IDetail]: any
}

// 3. Apply the type to an object literal
const control: DetailType = {
    name: [],
    enabled: []
}

I repeat this pattern quite often, and I'm wondering is there a way to generalize the 2nd step - possibly using generics ?

Well you can just make your type generic:

interface IDetail {
  name: string;
  enabled: boolean;
}

type Generic<T> = { [key in keyof T]: any };

const controlGeneric: Generic<IDetail> = {
  name: [],
  enabled: []
};

You can make a special generic type:

type WrapMyType<T, V> = { [key in keyof T]: V };

const control: WrapMyType<IDetail, any> = {
  name: [],
  enabled: [],
};

If you don't want to lose the types you can use this approach

type DetailType<T> = { [key in keyof T]: T[key] };

const control: DetailType<IDetail> = {
    name: [], // must be string
    enabled: [] // must be boolean
}

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