tswoes10895
tswoes10895

Reputation: 21

TypeScript do not require all index properties

I have the following code:

type AZ = 'a'|'b'|'c'|'d'| ... |'z'; // union of many types

type Mapping = {
  [K in AZ]: string;
}

const obj: Mapping = { // error, missing properties 'c', 'd', etc.
  a: '',
  b: ''
};

This lets me constrain props of obj to only those matching the union, but it forces me to list them all. If I do this instead:

type Mapping = {
  [K in AZ]?: string;
}

Now I don't have to supply every prop, but the resulting prop types contain undefined. How can I express that I want to only supply some keys from AZ, but if they are supplied, they should not be undefined? In other words, I want:

const obj: Mapping = { // ok
  a: '',  // checks 'a' as string
  b: ''   // checks 'b' as string
  bad: '' // error 'bad' not in AZ
  // no additional props needed
};

... without having to use an assertion like obj[prop]!.

PS: is this related to https://github.com/microsoft/TypeScript/issues/13195 ?

Upvotes: 2

Views: 91

Answers (0)

Related Questions