Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript mapped type - cannot add additional properties [duplicate]

Tags:

typescript

Suppose I have a type definition like this:

Person which must have either name or fullname property defined

type Person = {
  [k in "name" | "fullname"]: string;
}; 

Suppose I want to add one more required property age, intuitively I'd write something like this:

type Person = {
  [k in "name" | "fullname"]: string;
  age: number; // This errors
}; 

However this syntax will not work, the only way is to use intersection operator & like this:

type Person = {
  [k in "name" | "fullname"]: string;
} & { age: number }; 

Am I missing something or intersection is the only way to define this additional property on top of the mapped type?

Playground here

like image 836
Cristian E. Avatar asked Apr 28 '26 02:04

Cristian E.


1 Answers

type Person = {
  [k in "name" | "fullname"]: string;
}; 

is a mapped type. It's a separate concept from an object literal type where you specify the name and type of each key.

Perhaps you confused mapped types with index signatures-

type Person = {
  age: number;
  [k: string]: string | number;
}; 

Though, I don't think that's what you want here. You either use mapped types and intersect with another type, or you explicitly write out the mapping-

type Person = {
  age: number;
  name: string;
  fullname: string;
};
like image 165
Chase Avatar answered Apr 29 '26 22:04

Chase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!