peter flanagan
peter flanagan

Reputation: 9830

Issue with typing object TypeScript - when using a predefined type with null

I have the following type.

type Team = 'liverpool' | 'manUtd' | 'arsenal' | null;

I then have the following object.

const teams: Record<Team, JSX.Element> = {
  liverpool: <Liverpool />,
  manUtd: <ManU />,
  arsenal: <Arsenal />,
};

If I use teams as the first part of the Record I see the following error:

Type 'Team' does not satisfy the constraint 'string | number | symbol'.
  Type 'null' is not assignable to type 'string | number | symbol'.ts(2344)

If I use Record<string, JSX.Element> it works fine.

Upvotes: 1

Views: 694

Answers (2)

Lu&#239;s
Lu&#239;s

Reputation: 2853

The type for Record is Record<K extends string | number | symbol, T>.

So the first type you provide to the Record must be either string, number or symbol. You can't assign null to it so your Team type does not satisfy the constraint. You should remove null from your Team type and it'll work like a charm.

Upvotes: 1

Shanon Jackson
Shanon Jackson

Reputation: 6581

Record<NonNullable<Team>, JSX.Element>

Let me know if this helps. this error appears because null is not a valid javascript object key type.

Upvotes: 2

Related Questions