Skip to content

Commit 92a9ca8

Browse files
authored
Merge pull request #107 from andnp/SimplifyIsAny
Simplify is any
2 parents 270b889 + 06b571a commit 92a9ca8

File tree

3 files changed

+41
-13
lines changed

3 files changed

+41
-13
lines changed

.github/CODEOWNERS

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
* @andnp
2-
* @Retsam
1+
* @andnp @Retsam

README.md

+39-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ npm install --save-dev simplytyped
2121

2222
**[Utils](#utils)**
2323

24-
[NoInfer](#noinfer) - [Nominal](#nominal) - [Nullable](#nullable) - [PromiseOr](#promiseor) - [UnionToIntersection](#uniontointersection)
24+
[NoDistribute](#nodistribute) - [NoInfer](#noinfer) - [Nominal](#nominal) - [Nullable](#nullable) - [PromiseOr](#promiseor) - [UnionToIntersection](#uniontointersection)
2525

2626
**[Functions](#functions)**
2727

@@ -522,6 +522,44 @@ test('Can get all keys between objects in a union', t => {
522522

523523
## Utils
524524

525+
### NoDistribute
526+
Prevent `T` from being distributed in a conditional type.
527+
A conditional is only distributed when the checked type is naked type param and T & {} is not a
528+
naked type param, but has the same contract as T.
529+
```ts
530+
test("can create a conditional type that won't distribute over unions", t => {
531+
type IsString<T> = T extends string ? "Yes" : "No";
532+
type IsStringNoDistribute<T> = NoDistribute<T> extends string ? "Yes" : "No";
533+
534+
/**
535+
* Evaluates as:
536+
* ("foo" extends string ? "Yes" : "No")
537+
* | (42 extends string ? "Yes" : "No")
538+
*/
539+
type T1 = IsString<"foo" | 42>;
540+
assert<T1, "Yes" | "No">(t);
541+
assert<"Yes" | "No", T1>(t);
542+
543+
/**
544+
* Evaluates as:
545+
* ("foo" | 42) extends string ? "Yes" : "No"
546+
*/
547+
type T2 = IsStringNoDistribute<"foo" | 5>;
548+
assert<T2, "No">(t);
549+
assert<"No", T2>(t);
550+
});
551+
552+
test("cannot be used to prevent a distributive conditional from distributing", t => {
553+
type IsString<T> = T extends string ? "Yes" : "No";
554+
// It's the defintion of the conditional type that matters,
555+
// not the type that's passed in, so this still distributes
556+
type Test = IsString<NoDistribute<"foo" | 42>>;
557+
assert<Test, "Yes" | "No">(t);
558+
assert<"Yes" | "No", Test>(t);
559+
});
560+
561+
```
562+
525563
### NoInfer
526564
Prevent `T` from being inferred in generic function
527565
```ts

src/types/predicates.ts

+1-10
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,4 @@ export type IsObject<T> = And<
3737
Not<IsArray<T>>>
3838
>;
3939

40-
// hmm...
41-
export type IsAny<T> =
42-
And<Not<IsArray<T>>,
43-
And<Not<IsBoolean<T>>,
44-
And<Not<IsNumber<T>>,
45-
And<Not<IsString<T>>,
46-
And<Not<IsFunction<T>>,
47-
And<Not<IsNil<T>>,
48-
Not<IsObject<T>>>>>>>
49-
>;
40+
export type IsAny<T> = 0 extends (1 & T) ? True : False;

0 commit comments

Comments
 (0)