I'm trying to write some function that converts a mongoose User
model to a string with bullet points:
// Simplified version so you get the idea
interface IUser {
name: string
}
function userDetails (user: IUser, keys: string[]): string {
return keys.map((k: string): string => {
return `- ${k} : ${user[k]}`
})
.join('\n')
}
But I'm having a strange compiler error, where user[k]
is underlined:
Index signature of object type implicitly has an 'any' type.
Is there a way to "force" typescript to admin that user[k]
is a string ?
I tried user[k] as string
or <string> user[k]
without success.
Also, if I remove the ${user[k]}
from the returned string, then the compiler stop complaining
Appart from the compiler error, everything works at runtime.
Thanks !
Try this:
function userDetails(user: IUser, keys: string[]): string {
let dic: { [prop: string]: string } = <any>user
return keys.map((k: string): string => {
return `- ${k} : ${dic[k]}`
})
.join('\n')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With