Skip to content
Advertisement

What can I replace ‘any’ with while declaring an object type in Typescript?

class ResistorColor 
{
  private colors: string[]

  public colorValues: any = {
    grey: 8,
    white: 9
  }
}

‘any’ there means Typescript should not care about its type.

I want to replace ‘any’ by a type. How do we give proper types to such objects in Typescript?

Advertisement

Answer

As others have mentioned, using any as a type annotation in TypeScript doesn’t help in writing safe code. It’s better to not write a type annotation in that case and let TypeScript infer the type through Type Inference.

If you wanted to provide an explicit type annotation for the colorValues variable. You could create an interface, which acts as a blueprint to define the properties you expect the object to have.

interface Colors {
  grey: number;
  white: number;
}

public colorValues: Colors = {
  grey: 8,
  white: 9
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement