Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Commit

Permalink
Fix strict-type-predicate for unknown (#4444)
Browse files Browse the repository at this point in the history
* Add tests for strict-type-predicates and unknown

* Fix unknown with strict-type-predicate

* Fix unknown literal
  • Loading branch information
ThomasdenH authored and adidahiya committed Jan 10, 2019
1 parent bc382bf commit 153aa43
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/rules/strictTypePredicatesRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,12 @@ function walk(ctx: Lint.WalkContext<void>, checker: ts.TypeChecker): void {

const exprType = checker.getTypeAtLocation(exprPred.expression);
// TODO: could use checker.getBaseConstraintOfType to help with type parameters, but it's not publicly exposed.
if (isTypeFlagSet(exprType, ts.TypeFlags.Any | ts.TypeFlags.TypeParameter)) {
if (
isTypeFlagSet(
exprType,
ts.TypeFlags.Any | ts.TypeFlags.TypeParameter | ts.TypeFlags.Unknown,
)
) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ declare function get<T>(): T;
typeof get<string | number>() === `stirng`;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [typeof]

typeof get<any>() === "unknown";
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [typeof]

let a: string, b: string;
typeof a === typeof b;
typeof a === b;
Expand Down
42 changes: 42 additions & 0 deletions test/rules/strict-type-predicates/unknown/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[typescript]: >= 3.0.0

declare function get<T>(): T;

// typeof
{
typeof get<unknown>() === "undefined";
typeof get<unknown>() === "boolean";
typeof get<unknown>() === "number";
typeof get<unknown>() === "string";
typeof get<unknown>() === "symbol";
typeof get<unknown>() === "function";
typeof get<unknown>() === "object";
}

// negation
{
get<unknown>() !== null;
get<unknown>() !== undefined;
}

// reverse left/right
{
"string" === typeof get<unknown>();

undefined === get<unknown>();
}

// type parameters
{
function f<T>(t: T) {
typeof t === "boolean";
}
}

const body: unknown = 'test';
if (typeof body === 'object')
console.log('a');

let test: unknown = undefined;
if (test !== undefined)
console.log('b');
5 changes: 5 additions & 0 deletions test/rules/strict-type-predicates/unknown/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"compilerOptions": {
"strictNullChecks": true
}
}
5 changes: 5 additions & 0 deletions test/rules/strict-type-predicates/unknown/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"strict-type-predicates": true
}
}

0 comments on commit 153aa43

Please sign in to comment.