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
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]);
}
}