简体   繁体   English

TypesScript:为什么 keyof {} 没有类型?

[英]TypesScript: Why does keyof {} have the type never?

I am confused by the keyof operator when applied to an empty object.当应用于空的 object 时,我对keyof运算符感到困惑。 Example code:示例代码:

const o = {};
const k : Array<keyof typeof o> = [];
// k has type never[]

Why is the type never ?为什么类型never I thought never is the return type of functions that never return.我认为 never 是永远不会返回的函数的返回类型。 Should the type not be any[] instead?类型不应该是any[]吗?

When changing the object like this, the type makes sense:像这样更改 object 时,类型有意义:

const o = {a: 1, b: 2};
const k : Array<keyof typeof o> = []; 
// k has the type ("a" | "b")[]

I found this behaviour when implementing a function that returns the typed keys of an object:我在实现返回 object 的键入键的 function 时发现了这种行为:

function getKeys(o: object) {
    return Object.keys(o) as Array<keyof typeof o>;
}

The function has the return type never[] but should actually have (keyof typeof o)[] if I am correct function 有返回类型never[]但如果我是正确的,实际上应该有(keyof typeof o)[]

EDIT: Ok, so, after the update the questions is clearer to me.编辑:好的,所以,更新后问题对我来说更清楚了。 The problem here is that you are not using generics, so you are literally asking TS for the keys of object , not of SOME object .这里的问题是您没有使用 generics,因此您实际上是在向 TS 询问object的密钥,而不是某些 object的密钥。

You can re-arrange the function in this way:您可以这样重新排列 function:

function getKeys<O extends {}>(o: O) {
    return Object.keys(o) as Array<keyof O>;
}

So that it will accept a generic object of type O, and in this case keyof O will be typed exactly Array<keyof O> .这样它将接受 O 类型的通用object,在这种情况下, keyof O将准确键入Array<keyof O> For example:例如:

const keys = getKeys({ a: 1, b: 2 });
// Now keys has type ("a" | "b")[]

Old answer before post edit:帖子编辑前的旧答案:

never represents a value that can never occur, like explained in the TS Doc . never表示永远不会出现的值,如TS Doc中所述。 This is the case, since there are no keys in the object.就是这种情况,因为 object 中没有键。 To understand it better, this statement from TS Doc may be helpful:为了更好地理解它,来自 TS Doc 的声明可能会有所帮助:

The never type is a subtype of, and assignable to, every type; never 类型是每个类型的子类型,并且可以分配给每个类型;

This means that, in this case, never is correctly a subtype of string, especially meaning "no string" and so "no key".这意味着,在这种情况下,never 正确地是字符串的子类型,尤其是“没有字符串”和“没有键”的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM