简体   繁体   English

打字稿联合类型推断

[英]Typescript union type inference

How would I achieve type inference in the following case: 在以下情况下如何实现类型推断:

type a = {
    foo: number;
    bar: string;
}

type b = {
    foo: string;
}

let baz: a | b;

if (baz.foo === 5) {
    baz.bar = "abc"; // baz type is still a | b, should be a
}

Apparently types cannot be inferred from the types of their properties, so you will need to define a type guard: 显然,无法从其属性的类型推断类型,因此您将需要定义类型保护:

type a = {
    foo: number;
    bar: string;
}

type b = {
    foo: string;
}

let baz: a | b;

function isA(x: a | b): x is a {
    return typeof x.foo === 'number';
}

if (isA(baz) && baz.foo === 5) {
    baz.bar = "123";
}

The isA type guard will tell TypeScript that you have checked baz s type yourself. isA类型防护将告诉TypeScript您已经检查了baz的类型。 Below is another way to achieve this with casts, but here you still need to cast baz for every usage which is probably not the best way to do this. 下面是通过强制转换实现此目标的另一种方法,但是在这里,您仍然需要为每种用法强制转换baz ,这可能不是实现此目标的最佳方法。

if ((baz as a).foo === 5) {
    (baz as a).z = "123";
}

More information about type guards can be found in the TypeScript docs . 有关类型保护的更多信息,请参见TypeScript文档

baz type is still a | baz类型仍然是| b, should be a b,应该是

Actually what the TypeScript compiler does is restricts property access of all unified types ( a | b ) to properties that exist on all of them, thus, baz.bar does not even compile because bar does not exist on type b . 实际上,TypeScript编译器所做的是将所有统一类型( a | b )的属性访问限制为所有统一类型( a | b )上存在的属性,因此baz.bar甚至不会编译,因为bar在类型b上不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM