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
CodePudding user response:
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]);
}
}
CodePudding user response:
I'm still thinking about this as whenever unions are involved in index signatures, it can be very tricky but one workaround (without an explicit type) is as follows:
function testFun(v: type1[] | type2[], yKey: string) {
for (const item of v) {
console.log(item[yKey as keyof typeof item]);
}
}
This way it types to the correct expected object. It's honestly not a solution I prefer though since you can't provide an explicit, usable type ahead of time so I'll think on this some more but it does get you going right now.