Undefined vs guards

advertisements

Given strict null checking and an interface like

export interface Foo {
    a?: string;
    b: string|undefined;
    c: string|null;
    d: string|undefined|null;
}
function bar(foo: Foo) { ... }

I expected a to behave similarly to either b, c or d. Instead, I found that a behaved differently from all of them.

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? Is there any way to achieve the optional property behavior on an interface without the ?: syntax?


Is this expected behavior?

Yes, I found a comment on github confirming that it's by design:

This is by design. A property can be omitted only if it was declared with a ? modifier.

Also, it does not depend upon strict null checks being turned on.

Is there any way to achieve the optional property behavior on an interface without the ?: syntax?

No, presumably because someone might find use for all 4 behaviors from your example.