Home > Back-end >  "[key in Keys]" works but not with any other extra key?
"[key in Keys]" works but not with any other extra key?

Time:11-12

Can someone explain me this ?

Typescript can detect clashes if same keys in an object. Then why extra keys are not allowed ?

Typescript Playground

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;
}

Playground

CodePudding user response:

Since extraKey also has string value, following should work

type Bar = {    
    [key in Keys | "extraKey"]: string;
}
  • Related