我对使用“?”
的意义差异感到有点困惑我看到了这个:
var foo?: number = "bar"
但也看到了这个:
function foo(bar: {baz: ?string}) { ... }
并且还看到了两者。
我读过关于不变量和可能的类型,但如果我理解正确,两个信号都有相同的含义,即:“这种类型是'X',但它可能是null或未定义“。
是对还是我弄错了?
答案 0 :(得分:3)
以下是您的大多数问题的答案:
// Don't know what this is, or why you would use it
// Error: undefined is incompatible with string
var foo1?: string = undefined;
// ?string means string, null, or undefined
var foo2: ?string = undefined;
type FooOptional = { foo?: string };
type FooMaybe = { foo: ?string };
// If it's optional it can be completely omitted
var foo3: FooOptional = {};
// It can also be explicitly set to undefined
var foo4: FooOptional = { foo: undefined };
// But not null!
var foo5: FooOptional = { foo: null };
// If it's a maybe type, it must be specified
// Error: property `foo` not found
var foo6: FooMaybe = {};
// But you can set it explicitly to null or undefined
var foo7: FooMaybe = { foo: null };
var foo8: FooMaybe = { foo: undefined };
通常(但不是在所有情况下)同时使用它们(例如{foo?: ?string}
)表示作者并不完全知道他们想要使用什么类型并且刚刚添加了问号,直到它typechecks。通常我发现,如果我认为通过,那么使用 可选属性或类型可能是有意义的,但不能同时使用。