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 };
Playground here
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With