如何指示对象可能没有在打字稿的关键

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

在流量,就有了下面的差异:

type Obj1 = { foo?: number }
type Obj2 = { foo: ?number }

第一种类型说,对象可能没有钥匙foo,但如果是的话那么foo保证是一个数字。第二种类型逆转这样的:foo是保证的对象,但其价值可能为空。

是否打字稿这两者之间区别?从我所知道的,它只是提供了第一种类型的语法,但它意味着两者的混合物foo可能不存在,如果它可能为空或未定义。

javascript typescript flowtype
2个回答
0
投票

在打字稿你会做这样的:

type Obj1 = { foo?: number }
type Obj2 = { foo: number | undefined }

1
投票

您可以通过使用别名和仿制药获得类似的行为:

type maybe<T> = T | undefined;

interface Obj {
  prop: maybe<number>
}

或者,如果你想允许null

type maybe<T> = T | undefined | null;

interface Obj {
  prop: maybe<number>
}
© www.soinside.com 2019 - 2024. All rights reserved.