Búsqueda de sitios web

typescript - Usando enums como un tipo genérico


Estoy intentando lograr una funcionalidad que se vea así:

enum MyEnum {
   ONE = "ONE", 
   TWO = "TWO"
}

interface MyInterface<T extends enum> { //Obviously wrong syntax
    value: T; //Use a single value of the enum
    values: Record<T, number>; //Use all of the keys of the enum
    optionalValues: Record<T?, number>; //Use only the keys of the enum, but not necessarily all of them. 
}


const a : MyInterface<MyEnum>  = {
    value: "ONE",  //OK
    values: {
       ONE: 1,    //OK
       TWO: 2, 
       THREE: 3 //NOT OK 
    }, 
    optionalValues: {
       ONE: 111,   //OK
       THREE: 3    //NOT OK 
    }
}

const b : MyInterface<MyEnum>  = {
    value: MyEnum.ONE,  //OK
    values: {
       ONE: 1,    //Not ok - not all enum values used
    }, 
    optionalValues: {
       [MyEnum.ONE]: 111,   //Ok, and generally this is the way I want to be using this. 
    }
}


Es decir, quiero poder usar enumeraciones como una forma de especificar una lista de claves, y luego definir interfaces como objetos que contengan esas claves.

es decir

const iceCreams = MyInterface<IceCreamFlavours> = {
   ...
}

const fruit = MyInterface<FruitTypes> = {
    ...
}

¿Cómo puedo lograr esto? Parece un caso de uso bastante común.

Respuesta #1

No hay ninguna restricción enum. Los enums pueden ser string o number, así que una restricción de string | number es lo mejor que podemos hacer:

interface MyInterface<T extends string | number> {
    value: T; //Use a single value of the enum
    values: Record<T, number>; //Use all of the keys of the enum
    optionalValues: Partial<Record<T, number>>; //Use only the keys of the enum, but not necessarily all of them. 
}

enum MyEnum {
   ONE = "ONE", 
   TWO = "TWO"
}

const a : MyInterface<MyEnum>  = {
    value: MyEnum.ONE,  //OK
    values: {
       [MyEnum.ONE]: 1,    //OK
       [MyEnum.TWO]: 2, 
       [MyEnum.THREE]: 3 //NOT OK 
    }, 
    optionalValues: {
       [MyEnum.ONE]: 111,   //OK
       [MyEnum.THREE]: 3    //NOT OK 
    }
}

También podemos usar los nombres de los miembros del enum, pero entonces tenemos que pasar el tipo del objeto contenedor del enum, no el tipo del enum.

interface MyInterface<T extends Record<keyof T, string | number>> { // enum like object 
    value: keyof T; //Use a single value of the enum
    values: Record<keyof T, number>; //Use all of the keys of the enum
    optionalValues: Partial<Record<keyof T, number>>; //Use only the keys of the enum, but not necessarily all of them. 
}

enum MyEnum {
ONE = "ONE", 
TWO = "TWO"
}

const a : MyInterface<typeof MyEnum>  = {
    value: "ONE",  //OK
    values: {
    "ONE": 1,    //OK
    "TWO": 2, 
    "THREE": 3 //NOT OK 
    }, 
    optionalValues: {
    "ONE": 111,   //OK
    "THREE": 3    //NOT OK 
    }
}