class ResistorColor
{
private colors: string[]
public colorValues: any = {
grey: 8,
white: 9
}
}“‘any”表示Typescript不应该关心它的类型。
我想将“any”替换为一个类型。我们如何在Typescript中为这样的对象赋予适当的类型?
发布于 2021-03-12 14:07:57
正如其他人所提到的,在TypeScript中使用any作为类型批注无助于编写安全代码。在这种情况下,最好不要编写任何类型注释,让TypeScript通过Type Inference推断类型。
如果您想要为colorValues变量提供显式类型批注。您可以创建一个接口,它作为一个蓝图来定义您期望对象具有的属性。
interface Colors {
grey: number;
white: number;
}
public colorValues: Colors = {
grey: 8,
white: 9
}发布于 2021-03-12 14:04:43
除非在绝对必要的情况下,否则您不希望使用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
);
}
}https://stackoverflow.com/questions/66594670
复制相似问题