It is advisable to avoid using the any
type unless absolutely necessary. By defining a variable as any
, TypeScript loses the ability to enforce typing rules, leading to potential misuse of the variable.
A better approach would be to define custom types for specific scenarios. For example, you can create a type Color
that represents all valid color names as strings. Then, use this type to strongly type your variables such as private colors: Color[]
and
public colorValues: Record<Color, number>
.
type Color = 'grey' | 'white';
class ResistorColor
{
private colors: Color[] = [];
public colorValues: Record<Color, number> = {
grey: 8,
white: 9
}
}
Check out an example in Typescript Playground
If you need to dynamically generate the type Colors
based on an array of color names, consider using the typeof
operator. This method allows you to derive the type from existing data sets and ensure type safety throughout your codebase.
const colors = ['grey', 'white'] as const;
type Color = (typeof colors)[number];
class ResistorColor {
public colorValues: Record<Color, number>;
constructor(baseVal: number = 0) {
this.colorValues = {} as Record<Color, number>;
colors.forEach(
color => this.colorValues[color] = baseVal
);
}
}
Explore the code snippet in Typescript Playground