【问题标题】:How to fix 'type is not assignable to any' when addressing a member解决成员问题时如何解决“类型不可分配给任何人”
【发布时间】:2023-02-10 23:30:56
【问题描述】:

我有这样的代码:

interface IFoo {
  bar: string;
  baz: number;
}

function f(foo: IFoo, name: 'bar' | 'baz', val: any) {
  foo[name] = val;   // <<< error: Type 'any' is not assignable to type 'never'.
}

如果我将“baz”的类型也更改为“string”,那么错误就消失了:

interface IFoo {
  bar: string;
  baz: string;
}

function f(foo: IFoo, name: 'bar' | 'baz', val: any) {
  foo[name] = val;   // fine
}

为什么会发生这种情况,是否有可能解决这个问题? 我正在寻找一种比将 name: 'bar' | 'baz' 替换为 name: string 更好的解决方案。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您必须确保 val 具有与提供的 name 相对应的正确类型。

    Typescript Playground Example

    interface IFoo {
      bar: string;
      baz: number;
    }
    
    function f<K extends keyof IFoo>(foo: IFoo, name: K, val: IFoo[K]) {
      foo[name] = val;
    }
    
    const foo: IFoo = {
        bar: '',
        baz: 0
    }
    
    f(foo, 'bar', 'abc')
    f(foo, 'baz', 1)
    console.log(foo);
    

    或更一般

    function f<T, K extends keyof T>(foo: T, name: K, val: T[K]) {
      foo[name] = val;
    }
    

    Playground Example

    【讨论】:

      猜你喜欢
      • 2022-06-24
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 2023-03-14
      • 2013-06-03
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      相关资源
      最近更新 更多