简体   繁体   English

对象和原始值之间的类型声明失败

[英]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. 我打算创建一个名为options的变量,该变量允许使用“ Option”数组或单个值(例如字符串)。

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. 我进行了一些研究,但没有找到这种情况的解决方案或解决方法。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM