Search code examples
angulartypescripttype-assertion

Type Assertion failing between Object and primitive value


I've created this interface.

interface Option {
  value: string|number;
  label: string|number;
}

I'm planning to create a variable called options that allows an Array of "Option" or a single value such a string.

I don't have any issue giving values to the variable.

const options: Array<Option|string> = [{value: 'a', label: 'A'}];

But when I try to use the variable, I get the following error:

const singleOption = options[0].value;

Property 'value' does not exist on type 'string | Option'. Property 'value' does not exist on type 'string'

I tried validating if the value is an Object or a string.

const singleOption = typeof options[0] !== 'string' ? options[0].value : options[0];

and also with type assertion but I'm still getting the same error.

 const singleOption = (<Option>options[0]).value ? options[0].value : options[0];

I made a little research but I didn't find a solution or workaround for this scenario.


Solution

  • The control flow unfortunately doesn't work with array access like that. It'll work if you assign the option to a variable first:

    const option = options[0]
    const singleOption = typeof option !== 'string' ? option.value : option;