Skip to content

Infer class type from keyof class type #37384

Closed
@harrysolovay

Description

@harrysolovay

TypeScript Version: 3.8.2

Search Terms: infer, class, type, from, keyof, class, member, prop, deduce

View on TS Playground

Description:

// define a class
class MyClass {
  a?: string;
  b?: string;
}

// get the union type of the class keys
type MyFieldKey = keyof MyClass; // "a" | "b"

// create a utility type to get the class type from a given key type
type ClassType<FieldKey extends string | symbol> =
  FieldKey extends keyof infer ClassType ? ClassType : never;

// get the class type from the key type
type MyClassInferred = ClassType<MyFieldKey>; // the problem...

In this example, one might expect for MyClassInferred to have a signature of MyClass. Instead it has the following signature: { a: any } | { b: any }.

Is this by design?

Thanks!

Kind regards,

Harry

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions