I have a library function which returns an array of objects:
function someLibraryFunc(): object[]
I need to access a property of type string inside the returned objects, but the compiler is complaining:
function myFunc(prop: string): string[] {
someLibraryFunc()
.map(obj => obj[prop] as string) // <-- compiler error
}
/*
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.
*/
I've tried to add index signature like so:
function myFunc(prop: string): string[] {
someLibraryFunc()
.map((obj: { [key: string]: string }) => obj[prop]) // <-- compiler error
}
/*
TS2345: Argument of type '(obj: { [key: string]: string; }) => string' is not assignable to parameter of type '(value: object, index: number, array: object[]) => string'.
Types of parameters 'obj' and 'value' are incompatible. Type 'object' is not assignable to type '{ [key: string]: string; }'.
Index signature is missing in type '{}'.
*/
I've tried also the following:
function myFunc(prop: string): string[] {
someLibraryFunc()
.map((obj: { [key: string]: string }, index: number, array: object[]) => obj[prop]) // <-- compiler error
}
/*
TS2345: Argument of type '(obj: { [key: string]: string; }) => string' is not assignable to parameter of type '(value: object, index: number, array: object[]) => string'.
Types of parameters 'obj' and 'value' are incompatible. Type 'object' is not assignable to type '{ [key: string]: string; }'.
Index signature is missing in type '{}'.
*/
What is the proper way to add index signature to the arguments in the map function?
myFunc("somePropertyNotPresentInReturnedObjects")to output? The typing ofmyFunc()says that needs to produce astring[], but I expect you're going to get anundefined[]at runtime. Do you have some desired constraint onpropthat you haven't mentioned?