BalB
BalB

Reputation: 127

TypeScript Record of custom type as Key

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>

Upvotes: 0

Views: 145

Answers (1)

Jap Mul
Jap Mul

Reputation: 18749

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

Upvotes: 1

Related Questions