aherve aherve - 2 months ago 13
Node.js Question

How to force the type of a variable in typescript?

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 !

Answer

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')
}
Comments