1

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:

https://www.typescriptlang.org/play?#code/C4TwDgpgBAkgJhOUC8UDeAoKUCWcBcUAzsAE44B2A5gNwYC+dGokUAqkRKSurgcWUpUo9KAB90WKADMcpEgDkAhgFsIhEuWp1sAGyWLV6gVtoMmAYwD2FElACunUoQ5cembHkIByAIzeAGilZeWBlNR8AKSsACwpAqX1DCKhvABErCATsaSsrQjJ7CAYgA

Noitidart
  • 35,443
  • 37
  • 154
  • 323

0 Answers0