Skip to content

Type guard on conditional parameter type #38863

@jer-sen

Description

@jer-sen

TypeScript Version: 3.9.2

Search Terms:

Expected behavior: No error, Typescript should guess that a variable of type T extends '1' ? '1' : never will never be false, so that NonFalse<TypeWithCondition<T>> is exactly the same than true | (T extends '1' ? '1' : never)

Actual behavior: Error on logNonFalse(a);

Related Issues: none

Code

type TypeWithCondition<T> = boolean | (T extends '1' ? '1' : never);

type NonFalse<T> = Exclude<T, false>;

function logNonFalse<T>(b: NonFalse<TypeWithCondition<T>>) {
    console.log(b);
};

function test1<T>(a: TypeWithCondition<T>) {
    if (a === false) throw new Error("Can't be false");
    logNonFalse(a);
    // Error : Argument of type 'true | ([T] extends ["1"] ? "1" : never)' is not assignable to parameter of type 'true'.
    //  Type '[T] extends ["1"] ? "1" : never' is not assignable to type 'true'.
    //    Type '"1"' is not assignable to type 'true'.(2345)
};
Output
"use strict";
function logNonFalse(b) {
    console.log(b);
}
;
function test1(a) {
    if (a === false)
        throw new Error("Can't be false");
    logNonFalse(a);
    // Error : Argument of type 'true | ([T] extends ["1"] ? "1" : never)' is not assignable to parameter of type 'true'.
    //  Type '[T] extends ["1"] ? "1" : never' is not assignable to type 'true'.
    //    Type '"1"' is not assignable to type 'true'.(2345)
}
;
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions