question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unions without discriminant properties do not perform excess property checking

See original GitHub issue

TypeScript Version: 2.7.0-dev.201xxxxx

Code

// An object to hold all the possible options
type AllOptions = {
    startDate: Date
    endDate: Date
    author: number
}

// Any combination of startDate, endDate can be used
type DateOptions =
    | Pick<AllOptions, 'startDate'>
    | Pick<AllOptions, 'endDate'>
    | Pick<AllOptions, 'startDate' | 'endDate'>

type AuthorOptions = Pick<AllOptions, 'author'>

type AllowedOptions = DateOptions | AuthorOptions

const options: AllowedOptions = {
    startDate: new Date(),
    author: 1
}

Expected behavior:

An error that options cannot be coerced into type AllowedOptions because startDate and author cannot appear in the same object.

Actual behavior:

It compiles fine.

Issue Analytics

  • State:open
  • Created 6 years ago
  • Reactions:40
  • Comments:32 (16 by maintainers)

github_iconTop GitHub Comments

16reactions
dragomirtitiancommented, Apr 3, 2019

@svatal I have a workaround for this in the form of StrictUnion. I also have a decent writeup of it here:

type UnionKeys<T> = T extends unknown ? keyof T : never;
type StrictUnionHelper<T, TAll> = T extends unknown ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;
type StrictUnion<T> = StrictUnionHelper<T, T>

type IItem = StrictUnion<{a: string} & ({b?: false} | { b: true, requiredWhenB: string })>

function x(i: IItem) { }

x({ a: 'a' })   // ok
x({ a: 'a', b: false }) // ok
x({ a: 'a', unknownProp: 1 })   // ok, failed because of unknown property
x({ a: 'a', b: false, requiredWhenB: "x"})  // ok, failed because of unknown property
x({ a: 'a', requiredWhenB: "x"})    // fails now
x({ a: 'a', requiredWhenB: true})    // fails now
x({ a: 'a', b: undefined, requiredWhenB: "x"})    // this one is still ok if strictNullChecks are off.
x({ a: 'a', b: true })  // ok, failed because of missing required property
x({ a: 'a', b: true, requiredWhenB: "x" })  // ok
6reactions
AnyhowStepcommented, Aug 12, 2019

Just thought I’d bring up another approach to “human-readability”,

type UnionKeys<T> = 
  T extends unknown ?
  keyof T :
  never;
  
type InvalidKeys<K extends string|number|symbol> = { [P in K]? : never };
type StrictUnionHelper<T, TAll> =
  T extends unknown ?
  (
    & T
    & InvalidKeys<Exclude<UnionKeys<TAll>, keyof T>>
  ) :
  never;

type StrictUnion<T> = StrictUnionHelper<T, T>

/*
type t = (
    {a: string;} & InvalidKeys<"b" | "c">) |
    ({b: number;} & InvalidKeys<"a" | "c">) |
    ({c: any;} & InvalidKeys<"a" | "b">)
*/
type t = StrictUnion<{a: string} | {b: number} | {c: any}>

/*
type noisyUnion = ({
    a: string;
    b: string;
    c: number;
} & InvalidKeys<"x" | "y" | "z" | "i" | "j" | "k" | "l" | "m" | "n">) | ({
    x: string;
    y: number;
    z: boolean;
} & InvalidKeys<"a" | "b" | "c" | "i" | "j" | "k" | "l" | "m" | "n">) | ({
    ...;
} & InvalidKeys<...>) | ({
    ...;
} & InvalidKeys<...>)
*/
type noisyUnion = StrictUnion<
    | {a:string,b:string,c:number}
    | {x:string,y:number,z:boolean}
    | {i:Date,j:any,k:unknown}
    | {l:1,m:"hello",n:1337}
>;

Playground

If InvalidKeys is too verbose, you can make the name as short as an underscore, Playground


With Compute,

export type Compute<A extends any> =
    {[K in keyof A]: A[K]} extends infer X
    ? X
    : never

type UnionKeys<T> = 
  T extends unknown
  ? keyof T
  : never;

type StrictUnionHelper<T, TAll> =
  T extends unknown
  ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>>
  : never;

type StrictUnion<T> = Compute<StrictUnionHelper<T, T>>

/*
type t = {
    a: string;
    b?: undefined;
    c?: undefined;
} | {
    b: number;
    a?: undefined;
    c?: undefined;
} | {
    c: any;
    a?: undefined;
    b?: undefined;
}
*/
type t = StrictUnion<{a: string} | {b: number} | {c: any}>

/*
type noisyUnion = {
    a: string;
    b: string;
    c: number;
    x?: undefined;
    y?: undefined;
    z?: undefined;
    i?: undefined;
    j?: undefined;
    k?: undefined;
    l?: undefined;
    m?: undefined;
    n?: undefined;
} | {
    x: string;
    y: number;
    z: boolean;
    a?: undefined;
    ... 7 more ...;
    n?: undefined;
} | {
    ...;
} | {
    ...;
}
*/
type noisyUnion = StrictUnion<
    | {a:string,b:string,c:number}
    | {x:string,y:number,z:boolean}
    | {i:Date,j:any,k:unknown}
    | {l:1,m:"hello",n:1337}
>;

Playground


I like the Compute approach when the union is not “noisy” (the ratio of invalid to valid keys is closer to 0 or 0.5).

I like the InvalidKeys approach when the union is “noisy” (the ratio of invalid to valid keys is closer to one or higher).

Read more comments on GitHub >

github_iconTop Results From Across the Web

typescript - No excess property check in discriminated union - Stack ...
I would expect TS to choose discriminant d1 , as it is the only property that exists in all three states and is...
Read more >
Documentation - TypeScript 2.0
A property access or a function call produces a compile-time error if the object or function is of a type that includes null...
Read more >
TypeScript 3.5 releases with 'omit' helper, improved speed ...
TypeScript has this feature of excess property checking in object literals. In the earlier versions, certain excess properties were allowed ...
Read more >
4. Objects - Learning TypeScript [Book] - O'Reilly
Object literal may only specify known properties, // and 'activity' does not exist in type 'Poet'. Note that excess property checks only trigger...
Read more >
Type narrowing and discriminating unions in TypeScript
1type EventDate = string | Date | number; function ... toISOString() // Property 'toISOString' does not exist on type 'string' }.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found