-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Typescript automatically distributes conditional types over unions when the checked type is a naked type param (e.g. `T extends /*...*/`). Sometimes this is undesirable: so `NoDistribute<T> extends /*...*/` will not distribute if T is a union.
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import test from 'ava'; | ||
import { assert } from '../helpers/assert'; | ||
|
||
import { NoDistribute } from '../../src'; | ||
|
||
test("can create a conditional type that won't distribute over unions", t => { | ||
type IsString<T> = T extends string ? "Yes" : "No"; | ||
type IsStringNoDistribute<T> = NoDistribute<T> extends string ? "Yes" : "No"; | ||
|
||
/** | ||
* Evaluates as: | ||
* ("foo" extends string ? "Yes" : "No") | ||
* | (42 extends string ? "Yes" : "No") | ||
*/ | ||
type T1 = IsString<"foo" | 42>; | ||
assert<T1, "Yes" | "No">(t); | ||
assert<"Yes" | "No", T1>(t); | ||
|
||
/** | ||
* Evaluates as: | ||
* ("foo" | 42) extends string ? "Yes" : "No" | ||
*/ | ||
type T2 = IsStringNoDistribute<"foo" | 5>; | ||
assert<T2, "No">(t); | ||
assert<"No", T2>(t); | ||
}); | ||
|
||
test("cannot be used to prevent a distributive conditional from distributing", t => { | ||
type IsString<T> = T extends string ? "Yes" : "No"; | ||
// It's the defintion of the conditional type that matters, | ||
// not the type that's passed in, so this still distributes | ||
type Test = IsString<NoDistribute<"foo" | 42>>; | ||
assert<Test, "Yes" | "No">(t); | ||
assert<"Yes" | "No", Test>(t); | ||
}); |