gpt4 book ai didi

typescript - 为什么可以索引类型为 never 的对象?

转载 作者:行者123 更新时间:2023-12-05 05:30:25 26 4
gpt4 key购买 nike

tsconfig.json 中启用了 strict 后,为什么 tsc 在索引 never< 类型的对象时不会发出错误?

const mystery = ({ foo: 1 } as never)

console.log(mystery['foo']) // no error
console.log(mystery.foo) // Property 'foo' does not exist on type 'never'.

export {}

Playground example

最佳答案

It's bug #41021 :

'never' (and probably 'void') shouldn't be silently indexable types

DanielRosenwasser commented on Oct 10, 2020

let x = [1, 2, 3, 4].forEach(x => { console.log(x));
x["hello"] = 123;

Expected: an error that x is possibly void or somethingActual: no errors


DanielRosenwasser commented on Oct 10, 2020

Actually, never seems to suffer from the same issue..

TypeScript 团队正在积极修复它,但尚无可用的修复方法。

Here's更简单的复制:

declare let mystery: never;

console.log(mystery["foo"]); // No error
console.log(mystery.foo); // Property 'foo' does not exist on type 'never'.

关于typescript - 为什么可以索引类型为 never 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74667505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com