简体   繁体   English

TypeScript-使用泛型创建自定义类型

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

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

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