Basic Question and Context
I'm trying to type an array of objects where each object has exactly one key from a set. For example:
const foo = [
{ a: 'foo' },
{ b: 'bar' },
{ c: 'baz' },
]
My first attempt was key in
a union:
type Foo = { [key in 'a' | 'b' | 'c']: string }[]
const foo: Foo = [
{ a: 'foo' },
{ b: 'bar' },
{ c: 'baz' },
]
This doesn't work as Typescript wants every object to have all the keys in the union:
type Foo = { [key in 'a' | 'b' | 'c']: string }[]
const foo: Foo = [
{ a: 'foo', b: 'bar', c: 'baz' },
{ a: 'foo', b: 'bar', c: 'baz' },
{ a: 'foo', b: 'bar', c: 'baz' },
]
My second attempt was:
type A = { a: string }
type B = { b: string }
type C = { c: string }
type Foo = (A | B | C)[]
const foo: Foo = [
{ a: 'foo' },
{ b: 'bar' },
{ c: 'baz' },
]
but, as jcalz points out, that still allows:
const foo: Foo = [{ a: 'foo', b: 'bar' }]
Is there a way to enforce that each object has exactly one key and that key is either a
or b
or c
?
Slightly more context
Our project is trying to read in this JSON to handle dynamic forms for address fields in different countries in React. When Typescript reads that JSON blob in, it gets most things wrong. Most importantly, it believes that the fields
key is not always an array and so doesn't let me .map
over it. So I decided to copy the JSON blob into our project and type it by hand. I'm trying to capture the fact that the fields
array is an array of objects that are either thoroughfare
, premise
, or locality
and that locality
is an array of objects that are either localityname
, etc.
const foo: Foo = [{a: "foo", b: "bar"}]
also. When you say "exactly" one key, do you mean "at least"? That is, your solution is equivalent to this, which may or may not be an answer to your question depending on your requirements.{ a: '', b: '' }
items. That being said I'm not sure if my typing needs to exclude that case. Basically I'm usingif ('a' in obj) { ... }
so in the case of{ a: '', b: '' }
my solution is order dependent but doesn't break because the source data doesn't have that case. That being said, let's assume I don't want to allow{ a: '', b: '' }
. I'll update the question :-)