得到错误TS2322:类型“ any”不能分配给类型“ never”

时间:2019-06-25 23:29:41

标签: reactjs typescript react-redux

执行此操作时,I get “ts-ignore - error TS2322: Type 'any' is not assignable to type 'never'

type Obj = {
  key1: number;
  key2: string;
  key3: string | null;
};
type Keys = keyof Obj;
function mutateObj(obj: Obj, key: Keys, value: any) {
  obj[key] = value;
}

我收到上面的错误。当我从key3删除null时,它可以正常工作。如果您执行key3?: string;,则会收到相同的错误。我知道我做错了事,它与null / undefined类型有关,但不确定如何解决。

更新:感谢您的实施。 实际用例是在React App中的沉浸式还原器内部, 我想知道是否有一种无需助手功能即可键入的方法。 (目前,我正在使用该函数更改第一个答案中的草稿。非常感谢!:-))

const myReducer = produce((draft:<Obj>, action:{type:”update_prop”; prop: Keys, value: any })=>{
  switch (action.type) {
    case “update_prop” :
      // below gets type error
      draft[action.prop] = action.value;
      return;
  }
})

1 个答案:

答案 0 :(得分:3)

您可以通过这种方式实现

type Obj = {
  key1: number;
  key2: string;
  key3: string | null;
};

function mutateObj<T extends Obj, K extends keyof T>(obj: T, key: K, value: T[K]) {
  obj[key] = value;
}

const o: Obj = {
    key1: 1,
    key2: '2',
    key3: null,
};

mutateObj(o, 'key1', 'zz');

此外,它将保留值的类型安全性。

相关问题