Home > Enterprise >  TypeScript Record of custom type as Key
TypeScript Record of custom type as Key

Time:12-01

I have a question regarding TypeScript records being used with a custom Type as a key. So Basically I have a custom type (a limited set of strings) which I want to use as keys for my record. And I want to initialize this record as empty.

type MyCustomType = 'property1' | 'property2';


class MyClass {
    public myRecord: Record<MyCustomType, number> = {};
}

but doing so throws:

Type '{}' is missing the following properties from type 'Record<MyCustomType, number>'

is there any way, maybe Partial<MyCustomType> as the record Keys that allows me to achieve this?

I want to avoid creating the record as Record<string, number>

CodePudding user response:

You can use type assertions to accomplish this

type MyCustomType = 'property1' | 'property2'
const myVar = <Record<MyCustomType, number>>{}
// or: const myVar = {} as Record<MyCustomType, number>
myVar.property2 = 1 // will work
myVar.property3 = 2 // won't work

CodePudding user response:

You're instanciating myRecord as an empty object but you already declared its type as Record<MyCustomType, number>.

Either hold off on creating the instance until you have your values. You could do this like that:

 class MyClass {
    public myRecord!: Record<MyCustomType, number>;
 }
 
 // somewhere later
 myRecord = new Record....

Or directly declare your variable:

class MyClass {
     public myRecord: Record<MyCustomType, number> = new Record...;
}

NOT RECOMMENDED: Alternatively you could allow your variable to be of type {}:

class MyClass {
    public myRecord: Record<MyCustomType, number> | {} = {};
}
  • Related