简体   繁体   English

联合上的错误类型断言

[英]Wrong type assertion on union

I do not understand why the type assertion is not working in this minimum reproducible example.我不明白为什么类型断言在这个最小可重现示例中不起作用。

Here is the Playground Link这是游乐场链接

type Letter = "A" | "B"

type Useless = {}

type Container<T> =
    Useless |
    {
        type: "container"
        value: T
    }

function transform<X extends Letter, Y extends Letter>(container: Container<X | Y>): asserts container is Container<X> {
    // custom logic
}

let container: Container<"A" | "B"> = undefined as any

// Asserts no B
transform<"A", "B">(container)

container // Container<"A" | "B">
          // Container<"A"> when Useless is commented
          // I want Container<"A">

I want container to have type Container<"A"> .我希望容器具有类型Container<"A">

When I remove the type Useless altogether, then it works as expected.当我完全删除Useless类型时,它会按预期工作。

When I replace type Useless by type Useless = { key: string } , my container has type Useless instead of Container<"A"> .当我用 type type Useless = { key: string }替换 type Useless时,我的容器的类型Useless而不是Container<"A">

How can I obtain the type Container<"A"> ?我怎样才能获得类型Container<"A">

im actually not super sure why typescript has some problems here i assume the union with a generic where the T has no affect sometimes trips it up我实际上不太确定为什么 typescript 在这里有一些问题我假设与泛型的联合,其中 T 没有影响有时会绊倒它

if you split it up it works for me.如果你把它分开,它对我有用。 i assume here that Useless always asserts?我在这里假设Useless总是断言?

type Letter = "A" | "B"

type Useless = {}

type Container<T> =
    {
        type: "container"
        value: T
    }

type Input<T> = Useless | Container<T>

function transform<X extends Letter, Y extends Letter>(container: Input<X | Y>): asserts container is Container<X> {
    // custom logic
}

let container: Input<"A" | "B"> = undefined as any

// Asserts no B
transform<"A", "B">(container)

container // Container<"A" | "B">
          // Container<"A"> when Useless is commented
          // I want Container<"A">

Playground 操场

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

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