ConstructorParameters<Type>

Pobiera typy parametrów konstruktora klasy jako krotkę.

Na tej stronie

Przykład

#
TypeScript
class Student {
  constructor(public name: string, public level = 1) {}
}

type StudentArgs = ConstructorParameters<typeof Student>
// type StudentArgs = [name: string, level?: number | undefined]

function createMany(rows: StudentArgs[]): Student[] {
  return rows.map((args) => new Student(...args))
}

const students = createMany([['Ania', 4], ['Kuba']])
console.log(students)
Wynik
[Student { name: 'Ania', level: 4 }, Student { name: 'Kuba', level: 1 }]

Definicja i zastosowanie

#

ConstructorParameters<Type> zwraca krotkę z typami parametrów konstruktora. Przyjmuje typ samej klasy, czyli typeof Badge, a nie typ jej instancji. Dla constructor(title: string, exp: number) wynikiem jest [title: string, exp: number].

To odpowiednik Parameters dla konstruktorów. Przydaje się w fabrykach i funkcjach, które tworzą obiekty za wywołującego: przyjmują dokładnie te same argumenty co new, więc zmiana konstruktora od razu aktualizuje ich typy.

Działa także z klasami abstrakcyjnymi i wbudowanymi konstruktorami, np. ConstructorParameters<ErrorConstructor>. Pojedynczy argument wyciągniesz indeksem: ConstructorParameters<typeof Student>[0].

Składnia

#
Składnia
type Argumenty = ConstructorParameters<typeof Klasa>

Parametry typu

#
  • Type

    typ konstruktora

    Typ klasy (typeof Klasa) albo innej funkcji wywoływanej przez new.

Więcej przykładów

#
Uniwersalna fabryka
TypeScript
function make<C extends new (...args: any[]) => any>(
  Cls: C,
  ...args: ConstructorParameters<C>
): InstanceType<C> {
  return new Cls(...args)
}

class Badge {
  constructor(public title: string, public exp: number) {}
}

const badge = make(Badge, 'Seria 7 dni', 50)
console.log(badge.title, badge.exp)

make(Badge, 'Seria 7 dni')
// Błąd: Expected 3 arguments, but got 2.
Wynik
Seria 7 dni 50
Zapomniane typeof
TypeScript
type Wrong = ConstructorParameters<Student>
// Błąd: Type 'Student' does not satisfy the constraint 'abstract new (...args: any) => any'.
//   Type 'Student' provides no match for the signature 'new (...args: any): any'.

Dobre praktyki

#
  • Pamiętaj o typeof. Sama nazwa klasy w pozycji typu oznacza instancję, a nie konstruktor.
  • W parze z InstanceType opisuje całe wywołanie new: jeden typ mówi, co wchodzi, a drugi, co powstaje. To wystarcza do napisania generycznej fabryki, jak w drugim przykładzie.

Powiązane hasła

#

Widzisz błąd albo brakuje przykładu? Napisz do nas.