aherve
aherve

Reputation: 4070

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 !

Upvotes: 4

Views: 19878

Answers (1)

Paleo
Paleo

Reputation: 23692

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

Upvotes: 2

Related Questions