如何将可空类型转换为不可空类型(在打字稿中)?

问题描述 投票:0回答:2

我想将可空类型转换为不可空类型。

例如,如果我有这样的类型:

const type A = {b: "xyz"} | null

然后我想提取:

{b:"xyz"}

通过这样做:

A!

但它不起作用(当然,

!
运算符适用于可为空的“变量”,而不是可为空的“类型”)。

有人可以帮我解决这个问题吗?谢谢!

typescript
2个回答
4
投票

如果您有类型:

type A = {b: "xyz"} | null

使用

NonNullable
将从联合类型中删除
null
undefined

type NonNullableA = NonNullable<A>

如果您只想删除

null
但仍保留
undefined
,您可以使用
Exclude
:

type NullExcludedA = Exclude<A, null>

在这种情况下,

NonNullableA
NullExcludedA
都会产生您想要的类型:

{b:"xyz"}

0
投票

我的问题是 rxjs 由于某种原因将 Promise 转换为 Observable(角度 17)。 enter image description here 必须使用函数正确转换类型

const notUndefined = <T> (a: T | void) => a as T;
observable.pipe(map(notUndefined)
© www.soinside.com 2019 - 2024. All rights reserved.