gpt4 book ai didi

当没有类型注释时,Typescript 会提示有区别的联合类型

转载 作者:行者123 更新时间:2023-12-04 09:33:27 24 4
gpt4 key购买 nike

在我看来, typescript 在没有任何类型注释的情况下无法识别可区分的联合类型。我错过了什么吗?有什么原因吗?

export type Stuff = AType | BType

export type AType = { status: Kind.A; name: string }

export type BType = { status: Kind.B; quantity: number }

export enum Kind {
A,
B,
}

function PlayWithStuff(stuff: Stuff) {
console.log('some stuff', stuff)
}

const stuff = {
status: Kind.B,
quantity: 2,
}

PlayWithStuff(stuff)
// ^^^^^
// Argument of type '{ status: Kind; quantity: number; }' is not assignable to parameter of type 'Stuff'.
// Type '{ status: Kind; quantity: number; }' is not assignable to type 'BType'.
// Types of property 'status' are incompatible.
// Type 'Kind' is not assignable to type 'Kind.B'.

const secondStuff: Stuff = {
status: Kind.B,
quantity: 2,
}

PlayWithStuff(secondStuff)
// OK, the type annotation on `secondStuff` fixes the problem

最佳答案

初始化对象字面量时,Typescript 会推断属性类型,但不会推断为常量,因为它们不是只读的。
所以stuff的类型将是 { status: Kind, quantity: number } ,因为您以后可以将其更改为:

const stuff = {
status: Kind.B,
quantity: 2,
};

stuff.status = Kind.A;
所以现在它不能分配给 BType (也不是 AType 就此而言)。
您可以使用 as const :
const stuff = {
status: Kind.B,
quantity: 2,
} as const;
现在类型推断为 { readonly status: Kind.B, readonly quantity: 2}它始终可分配给 BType。
或者你可以做你所做的,只是给它类型注释:
const stuff: BType = {
status: Kind.B,
quantity: 2,
};

stuff.status = Kind.A; // Errors

关于当没有类型注释时,Typescript 会提示有区别的联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62710875/

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