TypesScript:为什么 keyof {} 没有类型? [英] TypesScript: Why does keyof {} have the type never?

查看:20
本文介绍了TypesScript:为什么 keyof {} 没有类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当应用于空对象时,我对 keyof 运算符感到困惑.示例代码:

I am confused by the keyof operator when applied to an empty object. Example code:

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

为什么类型是never?我认为 never 是永远不会返回的函数的返回类型.类型不应该是 any[] 吗?

Why is the type never? I thought never is the return type of functions that never return. Should the type not be any[] instead?

当像这样改变对象时,类型是有意义的:

When changing the object like this, the type makes sense:

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:

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

该函数具有返回类型 never[] 但实际上应该具有 (keyof typeof o)[] 如果我是正确的

The function has the return type never[] but should actually have (keyof typeof o)[] if I am correct

推荐答案

好的,更新后问题对我来说更清楚了.这里的问题是您没有使用泛型,因此您实际上是在向 TS 询问 object 的键,而不是 SOME 对象 的键.

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.

你可以这样重新排列函数:

You can re-arrange the function in this way:

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

这样它就会接受一个 generic 类型 O 的对象,在这种情况下 keyof O 将被准确地输入 Array.例如:

So that it will accept a generic object of type O, and in this case keyof O will be typed exactly Array<keyof O>. For example:

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

帖子编辑前的旧答案:

never 表示永远不会出现的值,如 TS 文档.这是这种情况,因为对象中没有键.为了更好地理解它,来自 TS Doc 的这个声明可能会有所帮助:

never represents a value that can never occur, like explained in the TS Doc. This is the case, since there are no keys in the object. To understand it better, this statement from TS Doc may be helpful:

never 类型是每个类型的子类型,并且可以分配给每个类型;

The never type is a subtype of, and assignable to, every type;

这意味着,在这种情况下,永远不会是字符串的正确子类型,尤其意味着无字符串"和无键".

This means that, in this case, never is correctly a subtype of string, especially meaning "no string" and so "no key".

这篇关于TypesScript:为什么 keyof {} 没有类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆