Skip to content

When infer K type from value type, occured an error in generic T[K]  #39972

Closed

Description

TypeScript Version: 3.9.2

Search Terms: ts type inference by value type, ts get property name from value type

Expected behavior:
this is an example code of typescriptlang.org : Distributive conditional types
I got K type that T[K] is Function. (following code:)

I expected TypeScript to be able to properly infer value type using this K type.
testForT1 and TestForGeneric should works fine.

Actual behavior:
I can't get V into the proper type using the K I got.
testForT1 function worked, but testForGeneric function occured that error.

Type 'T[{ [K in keyof T]: T[K] extends Function ? K : never; }[keyof T]]' is not assignable to type 'Function'.
  Type 'T[T[keyof T] extends Function ? keyof T : never]' is not assignable to type 'Function'.
    Type 'T[keyof T]' is not assignable to type 'Function'.
      Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'Function'.
        Type 'T[string]' is not assignable to type 'Function'.(2322)

Related Issues:

Code

type FunctionPropertyNames<T> = {
  [K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;

interface T1 {
    method(): string;
    method2(): number;
}

function testForT1(data: T1, key: FunctionPropertyNames<T1>): Function {
    return data[key];
}


function testForGeneric<T>(data: T, key: FunctionPropertyNames<T>): Function {
    return data[key];
}
Output
"use strict";
function testForI1(data, key) {
    return data[key];
}
function testForGeneric(data, key) {
    return data[key];
}
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions