联合未定义 vs 类型保护
Union undefined vs type guards
给定严格的空检查和类似
的接口
export interface Foo {
a?: string;
b: string|undefined;
c: string|null;
d: string|undefined|null;
}
function bar(foo: Foo) { ... }
我预计 a
的行为类似于 b
、c
或 d
。相反,我发现 a
的行为与他们所有人都不同。
bar({b: undefined, c: null, d: undefined}); // works
bar({c: null, d: undefined}); // 'b' is missing in type '{...}'
bar({b: undefined, d: undefined}); // 'c' is missing in type '{...}'
bar({b: undefined, c: null}); // 'd' is missing in type '{...}'
这是预期的行为吗?有什么方法可以在没有 ?:
语法的情况下在接口上实现可选的 属性 行为?
Is this expected behavior?
是的,我发现 a comment on github 确认这是设计使然:
This is by design. A property can be omitted only if it was declared
with a ? modifier.
此外,它不依赖于打开严格的空值检查。
Is there any way to achieve the optional property behavior on an
interface without the ?: syntax?
不,大概是因为有人可能会发现您示例中的所有 4 种行为都有用处。
在这种情况下,即使 属性 a
假定 b
的类型相同,如果您想要一个可选的 属性。
对于结构类型检查,类型 string|undefined
不能保证此 属性 是可选的。
所以,这是预期的行为。
给定严格的空检查和类似
的接口export interface Foo {
a?: string;
b: string|undefined;
c: string|null;
d: string|undefined|null;
}
function bar(foo: Foo) { ... }
我预计 a
的行为类似于 b
、c
或 d
。相反,我发现 a
的行为与他们所有人都不同。
bar({b: undefined, c: null, d: undefined}); // works
bar({c: null, d: undefined}); // 'b' is missing in type '{...}'
bar({b: undefined, d: undefined}); // 'c' is missing in type '{...}'
bar({b: undefined, c: null}); // 'd' is missing in type '{...}'
这是预期的行为吗?有什么方法可以在没有 ?:
语法的情况下在接口上实现可选的 属性 行为?
Is this expected behavior?
是的,我发现 a comment on github 确认这是设计使然:
This is by design. A property can be omitted only if it was declared with a ? modifier.
此外,它不依赖于打开严格的空值检查。
Is there any way to achieve the optional property behavior on an interface without the ?: syntax?
不,大概是因为有人可能会发现您示例中的所有 4 种行为都有用处。
在这种情况下,即使 属性 a
假定 b
的类型相同,如果您想要一个可选的 属性。
对于结构类型检查,类型 string|undefined
不能保证此 属性 是可选的。
所以,这是预期的行为。