xinli
xinli

Reputation: 43

how to define the types of a part of the properties of an object literal?

here I have the following code

const selectOptions = {
  mode: isTag ? 'tags' : 'combobox',
  ... //other stuff
}

return (<Select {...selectOptions}>...</Select>);

The mode is inferred as string by TypeScript but Select only takes type ModeOption = "default" | "multiple" | "tags" | "combobox" so there's an error.

My current way is by doing mode: (isTag ? 'tags' : 'combobox') as ModeOption. But I want to avoid using as, is there a better method? How to define the type of only several properties of an object literal?

Upvotes: 0

Views: 59

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371168

For the general case of when you want to avoid automatic type widening, you can use as const:

const selectOptions = {
  mode: (isTag ? 'tags' as const : 'combobox' as const),
}

Unlike other uses of as which indicate that you're asserting a type based on extra information not available to the compiler, as const is not potentially type-unsafe - all it does is tell TS not to widen the type, so don't be afraid to use it.

Upvotes: 2

Related Questions