Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
TypeScript: type of class that implements a certain interface or method

Goal

I wanna have a type that describes an object with values of type: Array<ClassRef> where ClassRef is any class that must implement a certain interface.

Approach

type KeyClassMap<SomeUnionType> = {
   [key in keyof SomeUnionType]: Array<ClassRef>
} 

type ClassRef = new (...args: any[]) => any // should extend that interface

interface I {
   [Symbol.hasInstance](hint: string): boolean
}

const _map: KeyClassMap<UnionType> = {
   myKey: [Date, MyOwnClass, MyOtherClass] // <- all these should have implemented Symbol.hasInstance to check with `instanceof` operator
}

Question

The example misses a declaration of a class that implements that interface. I am not sure how to do that.

Each class should only implement this one method ([Symbol.hasInstance]) to check if a value is an instance of that class.

I would like to know how to declare a type of a class that implements that interface or any other way to describe a class that has this method.

I assume that this is not really possible, so I appreciate any other tips.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When defining your ClassRef type you are really specifying the type of its constructor function. As the constructor function returns an instance of the class you can force the class to implement a specific interface by forcing the return value of its constructor to implement that interface. Your code should look like this:

type ClassRef<T> = new (...args: any[]) => T;

type KeyClassMap<SomeUnionType> = {
   [key in keyof SomeUnionType]: Array<ClassRef<I>>
} 

If you want to use the KeyClassMap type in other places as well, you can of course add another generic to it instead of statically using the I interface.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda