【问题标题】:Typescript Type 'string' is not assignable to type 'never'. error打字稿类型“字符串”不可分配给类型“从不”。错误
【发布时间】:2022-01-14 10:31:09
【问题描述】:

我想做的就是这么简单。

在下面的例子中,

interface InterfaceA { a: string, b: number }
interface InterfaceB { c: keyof InterfaceA }

const testMethod = (test: InterfaceB) => {
      const TestObject: InterfaceA = { a: '', b: 1 }

      TestObject[test.c] = 
    }

导致 'Type 'any' is not assignable to type 'never'' 错误。

我认为 test.c 可以在 TestObject 中赋值,因为 c 是接口 A 的键。

我怎样才能让事情顺利进行?

【问题讨论】:

  • 能否请您编辑您的问题以包含一个完整且可验证的示例。您目前提供的内容不足以让我们为您提供帮助。使用typescript playground,您可以在问题中包含指向工作示例的链接。
  • @Olian04 感谢您的建议!我用一个更简单的问题编辑了我的问题。

标签: string typescript types typescript-never


【解决方案1】:

您收到此错误是因为test.c 的类型不能比keyof InterfaceA 更窄。换句话说,如果我们尝试分配给TestObject[test.c],打字稿将无法确定我们是否需要分配stringnumber。所以它确定该类型必须同时是所有有效类型,在本例中为number & string。但是,任何值都不能同时是 numberstring,因此结果类型最终为 never(参见 this playground 示例)。

我们可以通过帮助 typescript 缩小 test.c 的实际类型来解决这个问题,如下所示:

interface InterfaceA { 
    a: string, 
    b: number
}
interface InterfaceB { 
    c: keyof InterfaceA
}

const testMethod = (test: InterfaceB) => {
    const TestObject: InterfaceA = { a: '', b: 1 }

    switch (test.c) {
        case 'a':
            TestObject[test.c] = 'foo';
            break;
        case 'b':
            TestObject[test.c] = 42;
            break;
    }
}

playground

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2022-01-17
    • 2020-02-07
    • 2018-02-02
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多