Unions without discriminant properties do not perform excess property checking
See original GitHub issueTypeScript 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:
- Created 6 years ago
- Reactions:40
- Comments:32 (16 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@svatal I have a workaround for this in the form of
StrictUnion
. I also have a decent writeup of it here:Just thought I’d bring up another approach to “human-readability”,
Playground
If
InvalidKeys
is too verbose, you can make the name as short as an underscore, PlaygroundWith
Compute
,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).