Can someone explain me this ?
Typescript can detect clashes if same keys in an object. Then why extra keys are not allowed ?
type Keys = "1" | "2" | "3" | "4" | "5";
// Works
type Foo = {
[key in Keys]: string;
};
// Errors
type Bar = {
extraKey : string;
[key in Keys]: string;
}
type Jar = {
[key in Keys]: string;
extraKey : string;
}
CodePudding user response:
You can't add fields in such way to mapped types, but you can use an intersection:
type Bar = {
extraKey : string;
} & {
[key in Keys]: string;
}
CodePudding user response:
Since extraKey
also has string value, following should work
type Bar = {
[key in Keys | "extraKey"]: string;
}