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'. } }La matriz v tiene muchos tipos de elementos que son un objeto, y quiero indexar estos objetos usando una yKey, pero el error siempre aparece
Cree una restricción genérica para el tipo de valor y luego usekeyof para restringir las claves permitidas:
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]); } }