-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Discriminated unions do not work with never / optional discriminant #38144
Description
TypeScript Version: 3.8.3
Search Terms:
- Discriminated Unions
- Negative Case
I am trying to write type specifications for the W3C Thing Definition spec, particularly DataSchema, which is a subset of json-schema.
DataSchema has several subclasses identified by a type key, but it can also be used without a type key, in which case only the base type properties should be allowed.
I have been unable to type this in such a way that a unifying type of all sub-interfaces plus base interface blocks the use of derived interface properties when no type is specified.
Code
Here is a simplified example:
interface Base {
title: string;
}
interface DerivedFoo extends Base {
type: "foo"
foo: number;
}
type MyType = DerivedFoo | Base;
// Expected an error here:
// `Base` does not define `foo`, and
// `DerivedFoo` does not match due to no `type` property.
// Actual behavior: Intellisense offers up 'foo'
const test: MyType = {
title: "test",
foo: 42
}
// We get an error here, as expected.
const whatIsFoo = test.foo;
Expected behavior:
There should be an error on test, as foo is not defined in Base and DerivedFoo should not be matched due to no type: "foo".
Actual behavior:
No error is reported when defining properties for test. Intellisense recognizes foo despite the lack of
Playground Link: example