Skip to content

Commit

Permalink
Merge pull request #107 from andnp/SimplifyIsAny
Browse files Browse the repository at this point in the history
Simplify is any
  • Loading branch information
andnp authored Jun 25, 2019
2 parents 270b889 + 06b571a commit 92a9ca8
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 13 deletions.
3 changes: 1 addition & 2 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
* @andnp
* @Retsam
* @andnp @Retsam
40 changes: 39 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ npm install --save-dev simplytyped

**[Utils](#utils)**

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

**[Functions](#functions)**

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

## Utils

### NoDistribute
Prevent `T` from being distributed in a conditional type.
A conditional is only distributed when the checked type is naked type param and T & {} is not a
naked type param, but has the same contract as T.
```ts
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);
});

```

### NoInfer
Prevent `T` from being inferred in generic function
```ts
Expand Down
11 changes: 1 addition & 10 deletions src/types/predicates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,4 @@ export type IsObject<T> = And<
Not<IsArray<T>>>
>;

// hmm...
export type IsAny<T> =
And<Not<IsArray<T>>,
And<Not<IsBoolean<T>>,
And<Not<IsNumber<T>>,
And<Not<IsString<T>>,
And<Not<IsFunction<T>>,
And<Not<IsNil<T>>,
Not<IsObject<T>>>>>>>
>;
export type IsAny<T> = 0 extends (1 & T) ? True : False;

0 comments on commit 92a9ca8

Please sign in to comment.