Skip to content

Type incorrectly inferred as union type when should be a string literal type #29373

Description

@gtkatakura-bysoft

TypeScript Version: 3.2.2

Search Terms: string literal type infer

Code

typeMethodNamesFrom<T>={[KinkeyofT]: T[K]extendsFunction ? K : never}[keyofT]constobj={a: ()=>{},b: ()=>{},c: 2}// CASE 1: PROBLEM?functionInfer1<TObject,TKeyextendsMethodNamesFrom<TObject>>(o: TObject,k: TKey){}Infer1(obj,'a')// TKey infer "a" | "b"// CASE 2: OKfunctionInfer2<TKeyextendsMethodNamesFrom<typeofobj>>(k: TKey){}Infer2('a')// TKey infer "a"// CASE 3: OK, explicity define generic typesInfer1<typeofobj,'a'>(obj,'a')// TKey infer "a"// CASE 4: OK, explicity define "a" as "a"Infer1(obj,'a'as'a')// TKey infer "a"// CASE 5: OK, enforces string in TKeyfunctionInfer3<TObject,TKeyextendsstring&MethodNamesFrom<TObject>>(o: TObject,k: TKey){}Infer3(obj,'a')// TKey infer "a"

Expected behavior: Infer TKey as "a" | "b" in case 1

Actual behavior: Should infer TKey as "a"

Playground Link:https://www.typescriptlang.org/play/index.html#src=type%20MethodNamesFrom%3CT%3E%20%3D%20%7B%0D%0A%20%20%5BK%20in%20keyof%20T%5D%3A%20T%5BK%5D%20extends%20Function%20%3F%20K%20%3A%20never%0D%0A%7D%5Bkeyof%20T%5D%0D%0A%0D%0Aconst%20obj%20%3D%20%7B%0D%0A%20%20a%3A%20()%20%3D%3E%20%7B%20%7D%2C%0D%0A%20%20b%3A%20()%20%3D%3E%20%7B%20%7D%2C%0D%0A%20%20c%3A%202%0D%0A%7D%0D%0A%0D%0A%2F%2F%20PROBLEM%3F%0D%0Afunction%20Infer1%3CTObject%2C%20TKey%20extends%20MethodNamesFrom%3CTObject%3E%3E(o%3A%20TObject%2C%20k%3A%20TKey)%20%7B%0D%0A%0D%0A%7D%0D%0A%0D%0AInfer1(obj%2C%20'a')%20%2F%2F%20TKey%20infer%20%22a%22%20%7C%20%22b%22%0D%0A%0D%0A%2F%2F%20OK%0D%0Afunction%20Infer2%3CTKey%20extends%20MethodNamesFrom%3Ctypeof%20obj%3E%3E(k%3A%20TKey)%20%7B%0D%0A%0D%0A%7D%0D%0A%0D%0AInfer2('a')%20%2F%2F%20TKey%20infer%20%22a%22%0D%0A%0D%0A%0D%0A%2F%2F%20OK%2C%20explicity%20define%20generic%20types%0D%0AInfer1%3Ctypeof%20obj%2C%20'a'%3E(obj%2C%20'a')%20%2F%2F%20TKey%20infer%20%22a%22%0D%0A%0D%0A%2F%2F%20OK%2C%20explicity%20define%20%22a%22%20as%20%22a%22%0D%0AInfer1(obj%2C%20'a'%20as%20'a')%20%2F%2F%20TKey%20infer%20%22a%22%0D%0A%0D%0A%2F%2F%20OK%2C%20enforces%20string%20in%20TKey%0D%0Afunction%20Infer3%3CTObject%2C%20TKey%20extends%20string%20%26%20MethodNamesFrom%3CTObject%3E%3E(o%3A%20TObject%2C%20k%3A%20TKey)%20%7B%0D%0A%0D%0A%7D%0D%0A%0D%0AInfer3(obj%2C%20'a')%20%2F%2F%20TKey%20infer%20%22a%22%0D%0A

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions