Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
Angular, pass generic type into another function. How to typed param?

I have function like:

getSomething<T>(value: T): any{
    const temp = this.doSomething<T>(value);
...
}

doSomething<T>(value: T): any {
    return value.replace(/\s/g, '');
}

Initially the value passed has a type specific type T, I know full well that in the final function it will be a string. However, doing it this way I can't use replace function. Help.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You need to say that value would have string methods. Like this:

getSomething<T extends string>(value: T): any{
    const temp = this.doSomething<T>(value);
...
}

doSomething<T extends string>(value: T): any {
    return value.replace(/\s/g, '');
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Think about your problem in the following way:

  1. How can I be sure that provided type has "replace()" method?
  2. What would happen if I provide different type e.g. number or null?

You have to somehow tell Typescript that you expect to get an argument that has method "replace()". You can do it by creating additional interface and mention that generic type extends that interface:

interface Replacable {
  replace: (regexp: RegExp, str: string) => string
}

function getSomething<T extends Replacable>(value: T): any{
    const temp = doSomething<T>(value);
    console.log(temp);
}

function doSomething<T  extends Replacable>(value: T): any {
    return value.replace(/\s/g, '');
}

Read more about Generic Constraints here: https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda