aherve aherve - 27 days ago 9
Node.js Question

How to force the type of a variable in typescript?

I'm trying to write some function that converts a mongoose

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]}`

But I'm having a strange compiler error, where
is underlined:

Index signature of object type implicitly has an 'any' type.

Is there a way to "force" typescript to admin that
is a string ?
I tried
user[k] as string
<string> user[k]
without success.

Also, if I remove the
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]}`