Skip to content

Type 'string' is not assignable to type 'Exclude<T, number>' when narrowing using generic #54175

Closed as not planned
@xsjcTony

Description

@xsjcTony

Bug Report

🔎 Search Terms

  • remove a type from generic union as return type
  • remove a type from generic union
  • remove a certain type from generic

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about <Can't find anything related>

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.1.0-dev.20230507#code/GYVwdgxgLglg9mABGEBbARgUwE4BU4DKU2MYA5gDy4B8AFAG4CGANiJgFyK4CUnAogA8IrACaYqAGmRos2aogDeAWABQidYmyYoIbEigBPAA6Y4wRE1aZEAXjuIA5Cgw4HiAPyIABgBIFltgBfL0ROAMwAblVA1VUAejjEEABnRjJMVVBIWAREZMxmTGhcTAEoWihSqE5k4lIyRAAfRAAlTDJBI25FVQ1EBMQoOBE4aNiVLOh4JEYwOCgACxwAMTBaRmwyTmdZJry68j22joEunrUNAcWYZMQbxEZoEBZmA0QAdzhsAGt6qXQQFA8nBUJgFnB3ogADKkawAJjut1qMGYzE0jBu9UGS0QOGwX16Gi0Oj0eQKRSgJTKtB2OHwRBI5HWm243CiKhiKnGkxySFpeEIBzIcKodHCnB4EtxZUwYBEt35Hm8flwwVCXHOfWJun0xlM5nCtnsThkriVvn8LCCITCVsiYy5E3AU1y-PpQoAzKKGHaJbwNVVZfLpC5sEraoyGlLlBd1NrSYYTGYLHajTZHPy3J4LeE1barOzOUA

💻 Code

function numberToString<T>(value: T): Exclude<T, number> {
    return typeof value === 'number' ? `${value}` : value;
//  ^^^^^^ Error
}

// usage
function selectText(text: string | RegExp) {
    // todo
}

function anotherFn(arg: number | string | RegExp) {
    // this is actually working, but somehow Line 2 is still raising the error
    return selectText(numberToString(arg));
}

🙁 Actual behavior

Type 'string | T' is not assignable to type 'Exclude<T, number>'.
  Type 'string' is not assignable to type 'Exclude<T, number>'

🙂 Expected behavior

There should be no issue, since T is extending any by default, hence string should absolutely be included in Exclude<T, number>, where it should be any type but without number

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions