10

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

2
  • 1
    Please see the answer to the question this duplicates for what's going on and how to approach this. Let me know if there's any outstanding issue. Good luck! Commented Oct 26, 2021 at 18:31
  • Thank you a lot for referencing the other answer it helped a lot! Commented Oct 26, 2021 at 20:00

1 Answer 1

10
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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for clean explanation. The referenced SO answer also helps!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.