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

310
Vistas
Typescript I can't index in the object ,which has many maybe object type
interface type1 {
    ttis: string,
    time: string
}

interface type2 {
    time: string,
    c2: number
}

type nameType1 = 'ttis' | 'time';

type nameType2 = 'c2' | 'time';

function testFun (v: type1[] | type2[], yKey: nameType1 | nameType2) {
    for (const item of v) {
        console.log(item[yKey]) // Property 'ttis' does not exist on type 'type1 | type2'.
    }
}

The v array has many types of element that is an object, and I want to index these objects using a yKey, but the error always up show

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

0

Create a generic constraint for the value type, and then use keyof to restrict the allowed keys:

interface Type1 {
    ttis: string,
    time: string
}

interface Type2 {
    time: string,
    c2: number
}

function testFun<T extends Type1 | Type2>(v: T[], yKey: keyof T) {
    for (const item of v) {
        console.log(item[yKey]);
    }
}
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