wude
wude

Reputation: 1

A question in Type inference in conditional types

type CtorParamsType<T> = T extends {
    new(...args: infer U);
} ? U : any;

class MyType {
    constructor(name: string, age: number) {

    }
}

type T1 = CtorParamsType<MyType> //any
type T2 = CtorParamsType<{ new(name: string, age: number); }> //[string, number]

In this sample , I expect T1 and T2 will have the same type.Why they are different?

Upvotes: 0

Views: 27

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250396

The type you are looking for already exists, it's called ConstructorParameters.

Your type would have worked too, the only issue is that MyType is the instance type. You want the constructor parameters of the class type, which you can access using typeof MyType


class MyType {
    constructor(name: string, age: number) {

    }
}

type T1 = ConstructorParameters<typeof MyType> // [string, number]
type T2 = ConstructorParameters<{ new(name: string, age: number): any }> // [string, number]

Playground Link

Upvotes: 3

Related Questions