在Flow中,以下内容之间是有区别的:
type Obj1 = { foo?: number }
type Obj2 = { foo: ?number }
第一种类型表示对象可能没有键foo
,但是如果有,则保证foo
是一个数字。第二种类型与此相反:foo
被保证在对象上,但是其值可以为null。
Typescript可以区分这两者吗?据我所知,它仅提供第一种类型的语法,但这意味着二者的混合:foo
可能不存在,如果存在,则可能为null或未定义。
答案 0 :(得分:1)
您可以通过使用别名和泛型来获得类似的行为:
type maybe<T> = T | undefined;
interface Obj {
prop: maybe<number>
}
或者如果您想允许null
type maybe<T> = T | undefined | null;
interface Obj {
prop: maybe<number>
}
答案 1 :(得分:0)
在TypeScript中,您可以这样做:
type Obj1 = { foo?: number }
type Obj2 = { foo: number | undefined }