ofir_aghai
ofir_aghai

Reputation: 3301

How can i create type with just part of predefined available keys?

How can i create type with just part of predefined available keys?

i do something like:

export type MyKeys = 'aa' | 'bb' | 'cc';

export type MyType = {
    [k in MyKeys]: any;
};

and use it:

let mySpecialObj: MyType = {
    aa: 'key',
    // bb: 'key', <-- without this for example
    cc: 'key'
}

( Other question: As i see here, this question are not the same because i meant for a type with iterator key declaration: [k in MyKeys]: any; )

Upvotes: 0

Views: 64

Answers (2)

ofir_aghai
ofir_aghai

Reputation: 3301

So i found the solution,

just to add question mark '?' in the end of the declaration of the key part like:

export type MyType = {
    [k in MyKeys]?: any;
};

Upvotes: 1

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249536

You can just mark all fields as optional:

export type MyKeys = 'aa' | 'bb' | 'cc';

export type MyType = {
    [k in MyKeys]?: any;
};

let mySpecialObj: MyType = {
    aa: 'key',
    cc: 'key'
}

Upvotes: 2

Related Questions