Is there a way to define that an array
['left', 'center', 'right']
is not a string[]
but Position[]
in this code example without storing it in a variable:
type Position = 'left' | 'center' | 'right';
const sidePositions: Position[] = ['left', 'center', 'right'].filter(p => p !== 'center');
Example is a very simplified version of what we are actually doing in our project, we cannot use just ['left', 'right']
array instead. The following workaround works but we won't get a TS error if we mistype some words and that can cause some human errors:
const sidePositions: Position[] = (['foo', 'bar', 'right'] as Position[]).filter(p => p !== 'center');
Of course it is possible to store the array in a typed variable first, but in our case it is less convenient. Here's a link to TS Playground