无需使用泛型即可推断特定于接口密钥的值类型

在以下代码段中
我有一个简单的查找功能,该功能可以查找对象并返回object [key]值

interface Bar {  
  abc: string;  
  def: boolean;  
}  

// Without generics - Case I
function lookup(data: Bar,key: keyof Bar) {
  return data[key];
}

// With generics - Case II
function lookup<K extends keyof Bar>(data: Bar,key: K) {
  return data[key];
}

const someData: Bar = {
  abc: 'abinash',def: true
};

type abcType = 'abc';
let x = lookup(someData,'abc' as abcType); // output - string | boolean instead of only string
// here I am trying to explicity pass that the key value is of type 'abc' to allow inferring as Bar['abc'],same as with generics,

使用泛型,TS可以推断对应的键查找的类型,因为 lookup(someData,'abc')等同于lookup (someData,'abc') 因此,“ abc”被替换为通用提及 查找ReturnType时,Bar [K]会转换为Bar ['abc'],TS可以正确告诉我函数调用的Bar ['abc']类型

没有泛型,查找的返回类型被约束为string |通过默认类型计算获得布尔值。

是否有可能不使用泛型来推断类型? (这是一个局限性,在某些情况下鼓励更多地使用泛型以获得更好的类型特异性)

mengdegong 回答:无需使用泛型即可推断特定于接口密钥的值类型

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3067161.html

大家都在问