gpt4 book ai didi

typescript - 为什么不是 {a : never} equivalent to never?

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

{a: never} 似乎可以简化为never。这样做可以解决我下面的问题。这是不可能的吗?

type A = {tag: 'A', value: number}
type B = {tag: 'B', value: boolean}
type N = {tag: never, value: string}

type Ntag = N["tag"] // never
type Nvalue = N["value"] // string
// Couldn't N["value"] be simplified to never because an object of type N could never exist?
// And thus, couldn't N be simplified to never?

type AN = A | N
type ANtag = AN["tag"] // "A"
type ANvalue = AN["value"] // Expected: number, Actual: string | number
// AN has to be an A, an object of type N can't exist. So why can't AN["value"] be simplified to number?

type AB = A | B
type NarrowToA = AB & {tag: 'A'} // Expected A, Actual: (A & {tag: "A"}) | (B & {tag: "A"})
type NarrowToATag = NarrowToA["tag"] // A
type NarrowToAValue = NarrowToA["value"] // Expected number, Actual number | boolean
// Again, NarrowToA has to be an A, an object of type B would never fit. So why can't NarrowToA["value"] be simplified to number?

Playground Link

最佳答案

感谢您的评论@zerkms!这让我意识到以下是 N 类型的有效值。因此,可能存在具有 never 类型属性的对象。

type N = {tag: never, value: string}

const n: N = {
get tag(): never {
while (true) {}
},

value: 'hi'
}

const nTag = n.tag; // Type: never
const nValue = n.value; // Type: string

关于typescript - 为什么不是 {a : never} equivalent to never?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61177932/

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