遇到错误类型any不能分配为never类型

时间:2020-09-11 09:32:06

标签: reactjs typescript

我的状态看起来像这样

export interface IState {
  relationType: string
  relatedTableId: number | null
  foreignKey: string
  throughTableId: string
  required: boolean
}

this.state = {
  relationType: props.relation ? props.relation.relation_type : 'parent_relation',
  relatedTableId: _.get(props, 'relation.related_table.id', null),
  foreignKey: _.get(props, 'relation.foreign_key') || '',
  throughTableId: _.get(props, 'relation.through_table_id') || '',
  required: props.relation ? true :false
}

当我尝试动态更改状态时,

  handleOnChange(
    selected: ValueType<SelectOption>,
    key: 'relationType' | 'throughTableId' | 'relatedTableId'
  ) {
      const currentState = { ...this.state }
      currentState[key] = (selected as SelectOption).value;
      this.setState({ ...currentState })
  }

在这里,TS抛出以下错误

“字符串”类型不能分配为“从不”类型

知道我可能做错了什么吗?

这就是“选择选项”的外观(如果有所区别)

type SelectOption = {
  value: string | number
  label: string
}

这是错误

enter image description here

3 个答案:

答案 0 :(得分:1)

您正在尝试将类型为string | number的值分配给该键的键不兼容。可以为他们分配stringnumber | null,但是他们都不能接受string | number

relationType: string
relatedTableId: number | null
throughTableId: string

除非您缩小selected.value的类型以确保您:

  1. 知道它是什么类型
  2. 将其分配给与缩小类型兼容的字段

TypeScript不允许您将其分配给您要尝试的任何字段。

编辑

正如sam256所说,之所以说“不可分配给never”是因为relationTyperelatedTableIdthroughTableId在类型上没有重叠,所以没有可以分配给所有三个值的值的类型。

例如,如果key"relationType" | "throughTableId",则不会是这种情况,因为在那种情况下,可以为currentState[key]分配类型为string的值,因为: / p>

currentState["relationType" | "throughTableId"]: string

答案 1 :(得分:1)

Typescript在这里确定一个真正的问题。如果您通过handleOnChange传递了一个“ selected.value”(该字符串是一个字符串,但是一个“ keytable”值却是“ relatedTableId”)怎么办?您的函数将尝试将字符串分配给数字。换句话说,您实际上在TS标记的代码中可能存在类型不匹配的情况。

我相信错误的措辞是因为TS推断出currentState [key]是字符串和数字的交集,而从不。

答案 2 :(得分:0)

Typescript指出您没有执行所有必需的类型检查。为了扩展其他答案,TS希望查看看起来更像以下的代码:

function handleOnChange(
    selected: ValueType<SelectOption>,
    key: 'relationType' | 'throughTableId' | 'relatedTableId'
) {
    const currentState = { ...this.state }
    const selectedValue = (selected as SelectOption).value
    if (key === 'relationType' || key === 'throughTableId') {
        if (typeof selectedValue === 'string') {
            currentState[key] = selectedValue
        }
    } 
    else {
        if (typeof selectedValue === 'number') {
            currentState[key] = selectedValue       
        } 
    }
}

上面使用了TS可以理解的显式类型检查,并且应该进行编译而不会出错。

相关问题