[英]TypeScript: `'keyof R'` is not assignable to type 'string' because it can be either 'string | number | symbol'
I have a function that takes a key of an object, is there a way to narrow the type of the key to only string
我有一个 function,它采用 object 的键,有没有办法将键的类型缩小为仅
string
function foo<R, K extends keyof R>(obj: R, key: K, array: string[]) {
array.push(key); // Error🚨: Type 'string | number | symbol' is not assignable to type 'string'.
// omit implementation details...
return obj[key];
}
So TS compiler says that 'keyof R'
is not assignable to type 'string' because it can be either 'string |所以 TS 编译器说
'keyof R'
不能分配给类型 'string' 因为它可以是 'string | number |编号 | symbol'.
象征'。 I wonder if there is a way to narrow its type to only
string
so we can exclude number
and symbol
from it.我想知道是否有办法将其类型缩小为仅
string
,以便我们可以从中排除number
和symbol
。
I tried this but it seems wrong syntactically我试过了,但在语法上似乎是错误的
function foo<R, K extends Extract(keyof R, string)>(obj: R, key: K, array: string[]) {
array.push(key);
// omit implementation details...
return obj[key];
}
Your generic syntax is wrong, Extract(A, B)
needs to be Extract<A, B>
, so function foo<R, K extends Extract<keyof R, string>>(obj: R, key: K, array: string[])
.你的通用语法是错误的,
Extract(A, B)
需要是Extract<A, B>
,所以 function foo<R, K extends Extract<keyof R, string>>(obj: R, key: K, array: string[])
。
That said there is really no reason to have your function generic on two things when you care about one object:也就是说,当您关心一个object 时,真的没有理由让您的 function 在两件事上通用:
function foo<R>(obj: R, key: Extract<keyof R, string>, array: string[]): void {
array.push(key);
}
Would work just as well and is much simpler.效果一样好,而且简单得多。
You need the second type if you want to return the object's value at the key, and you end up with:如果你想在键处返回对象的值,你需要第二种类型,你最终会得到:
function foo<R, T extends Extract<keyof R, string>>(obj: R, key: T, array: string[]): R[T] {
array.push(key);
return obj[key];
}
foo({x: 3, y: 5}, 'x', array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.