I'm trying to define a type that is either { id: string}
or { firstName: string; lastName: string}
.
So I wrote this code:
type Ided = {
id: string;
};
type User = { id: string } | {
firstName: string;
lastName: string;
};
const user: User = {
id: '1',
firstName: 'John',
lastName: 'Doe',
foo: true
}
However this code is allowing all three keys of id
firstName
and lastName
. It is only throwing error for the key of foo
. Is there a way to accomplish this union?
This is the typescript playground: