class ResistorColor
{
private colors: string[]
public colorValues: any = {
grey: 8,
white: 9
}
}
"any"表示Typescript不应该关心其类型。
我想用类型替换"any"。我们如何在Typescript中为这些对象指定正确的类型?
除非在绝对必要的情况下,否则您不想使用any
。any
意味着一个类型可以是任何东西,因此您没有关于该类型的信息。Typescript无法检查变量是否被滥用,因为您说过"任何事情都会发生";。
有很多方法可以正确地键入,但这里有一个想法。您可以定义一个type Color
,它是所有有效颜色的string
名称的并集。您的private colors
是这些的数组,所以它应该是Color[]
。您的public colorValues
是颜色到数字的映射,因此您可以使用内置的实用程序类型Record
将其描述为Record<Color, number>
,这是一个键类型为Color
、值类型为number
的对象。(如果对象中不存在所有颜色,则会使用Partial<Record<Color, number>>
进行不完整的映射(。
type Color = 'grey' | 'white';
class ResistorColor
{
private colors: Color[] = []; // initial value avoids "not assigned in the constructor" error
public colorValues: Record<Color, number> = {
grey: 8,
white: 9
}
}
打字游戏场链接
在颜色名称数组上使用typeof
来获得type Colors
可能是有意义的,但我不知道在代码中的哪里会有这样一个具有所有颜色的数组或对象。例如,如果您使用某个基值初始化了colorValues
,这可能是有意义的。
const colors = ['grey', 'white'] as const; // use as const to preserve string literals
type Color = (typeof colors)[number]; // indexed access by [number] to get the element type
// resolves to: type Color = "grey" | "white"
class ResistorColor {
public colorValues: Record<Color, number>;
constructor(baseVal: number = 0) {
this.colorValues = {} as Record<Color, number>; // need to make an `as` assertion when starting with an incomplete object
colors.forEach(
color => this.colorValues[color] = baseVal
);
}
}
打字游戏场链接
正如其他人所提到的,在TypeScript中使用any
作为类型注释无助于编写安全的代码。在这种情况下,最好不要写类型注释,让TypeScript通过类型推断来推断类型。
如果要为colorValues
变量提供显式类型注释。您可以创建一个接口,它充当一个蓝图来定义您期望对象具有的属性。
interface Colors {
grey: number;
white: number;
}
public colorValues: Colors = {
grey: 8,
white: 9
}