XYZ
XYZ

Reputation: 27387

How to define Object Key as String Type

Below is the function signature,

export function getVideoBooleansParamsString(videoBooleans: {
  string: { label: string; value: boolean }
}): string {}

And this is the arg I am trying to pass into,

const videoBooleans = { video: { label: 'video', value: true } }

And it produce the following error,

(63,33): error TS2345: Argument of type '{ exchange: { filterType: string; filterValues: string[]; }; }' is not assignable to parameter of type '{string: FilterModel; }'.
  Property 'string' is missing in type '{ exchange: { filterType: string; filterValues: string[]; }; }'.

What I intend to declare is an object whatever the key is has the content of { label: string; value: boolean }

Upvotes: 0

Views: 912

Answers (2)

Frank Modica
Frank Modica

Reputation: 10516

The way you have it defined now expects the following:

const videoBooleans = { string: { label: 'video', value: true } };

getVideoBooleansParamsString(videoBooleans);

You can define it like this, if you want the key to be any string:

export function getVideoBooleansParamsString(videoBooleans: {
  [key: string]: { label: string; value: boolean }
}): string { }

Or like this, to be more specific:

export function getVideoBooleansParamsString(videoBooleans: {
  video: { label: string; value: boolean }
}): string { }

You can also define an interface, which can make the function signature a bit cleaner:

interface MyVideoType {
   [key: string]: { label: string, value: true };
}

export function getVideoBooleansParamsString(videoBooleans: MyVideoType): string { }

const video: MyVideoType = { video: { label: 'video', value: true } };

getVideoBooleansParamsString(video);

Upvotes: 3

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249476

You need to define an index for your parameter type :

export function getVideoBooleansParamsString(videoBooleans: {
  [name :string] : { label: string; value: boolean }
}): string {}

Upvotes: 1

Related Questions