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

Fix strict-type-predicate for unknown #4444

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}