TypeScript: type unknown properties


Given a JavaScript object with unknown property names but known property values, how can we type the object in TypeScript?

Object Literal

Unknown properties for object literals can be typed like so:

// index.ts
type Props = {
  [key: string]: string;
};

Example use case:

const props: Props = {
  id: 'foo',
};

Record

The Record utility type also works as an alternative here:

// index.ts
type Props = Record<string, string>;

Example use case:

const props: Props = {
  id: 'foo',
};

Intersection

To type both known and unknown properties, use intersection types:

// index.ts
type Props = Record<string, string> & {
  style: Record<string, string>;
};

Example use case:

const props: Props = {
  id: 'foo',
  style: {
    color: '#bada55',
  },
};


Please support this site and join our Discord!