gpt4 book ai didi

typescript - 区分联合类型

转载 作者:行者123 更新时间:2023-12-01 10:17:38 25 4
gpt4 key购买 nike

为什么我不能仅根据成员 x 是字符串而不是数字的信息来区分联合?为什么我必须使用文字类型?

type A = { x: string ; y: string }
type B = { x: number ; y: number }
type C = A | B

function fn(p: C) {
if (typeof p.x === 'string') {
// Typescript is unable to infer p as A
// Typescript infer p.y as (string | number), why not just string ?
}
// Typescript is capable of inferring p.x as number - good
// But cannot infer p.y as number, why ?
}

对我来说,用 {x:string,y:number} 这样的类型调用函数是不可能的,那么为什么 typescript 假设这是可能的呢?

最佳答案

不是直接解释为什么 Typescript 编译器不能通过 typeof 区分联合类型,而是 handbooks说:

There are three ingredients:

  1. Types that have a common, singleton type property — the discriminant.
  2. A type alias that takes the union of those types — the union.
  3. Type guards on the common property.

因此,为了缩小正确类型的范围,单例类型 属性是必要的。我会使用自定义类型保护:

type A = { x: string ; y: string }
type B = { x: number ; y: number }
type C = A | B

function isA(obj: C): obj is A {
return typeof obj.x === 'string';
}

function isB(obj: C): obj is B {
return typeof obj.x === 'number';
}

function fn(p: C) {

if (isA(p)) {
// ...
}

if (isB(p)) {
// ...
}

}

关于typescript - 区分联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59840445/

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