Skip to content

Discriminated unions do not work with never / optional discriminant #38144

@RoboPhred

Description

@RoboPhred

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions