patterntypescriptCritical
Define a list of optional keys for Typescript Record
Viewed 0 times
typescriptkeysforoptionallistrecorddefine
Problem
I want to type an object which can only have keys 'a', 'b' or 'c'.
So I can do it as follows:
They are all optional!
Now I was wondering if this can be written with
The only issue is that all keys need to be defined. So I ended up with
This works, but I can imagine there is a better way to do this without Partial. Is there an other way to make the keys optional inside Record ?
So I can do it as follows:
Interface IList {
a?: string;
b?: string;
c?: string;
}They are all optional!
Now I was wondering if this can be written with
Record in just one linetype List = Record;The only issue is that all keys need to be defined. So I ended up with
type List = Partial>;This works, but I can imagine there is a better way to do this without Partial. Is there an other way to make the keys optional inside Record ?
Solution
There is no way to specify the optionality of members of
You can define your own type if this is a common scenario for you:
Or you can define
Record. They are required by definitiontype Record = {
[P in K]: T; // Mapped properties are not optional, and it's not a homomorphic mapped type so it can't come from anywhere else.
};You can define your own type if this is a common scenario for you:
type PartialRecord = {
[P in K]?: T;
};
type List = PartialRecordOr you can define
PartialRecord using the predefined mapped types as well:type PartialRecord = Partial>Code Snippets
type Record<K extends keyof any, T> = {
[P in K]: T; // Mapped properties are not optional, and it's not a homomorphic mapped type so it can't come from anywhere else.
};type PartialRecord<K extends keyof any, T> = {
[P in K]?: T;
};
type List = PartialRecord<'a' | 'b' | 'c', string>type PartialRecord<K extends keyof any, T> = Partial<Record<K, T>>Context
Stack Overflow Q#53276792, score: 207
Revisions (0)
No revisions yet.