Javascript 我可以替换什么';任何';在Typescript中声明对象类型时使用?
“any”表示Typescript不应该关心它的类型Javascript 我可以替换什么';任何';在Typescript中声明对象类型时使用?,javascript,typescript,Javascript,Typescript,“any”表示Typescript不应该关心它的类型 我想用类型替换“any”。我们如何在Typescript中为这些对象指定适当的类型?除非在绝对必要的情况下,否则您不想使用任何any意味着一个类型可以是任何东西,因此您不知道该类型是什么。Typescript无法检查变量是否被滥用,因为您已经说过“一切正常” 有很多方法可以正确地键入,但这里有一个想法。您可以定义类型颜色,它是所有有效颜色的字符串名称的并集。您的private colors是这些颜色的数组,因此它应该是Color[]。您的pu
我想用类型替换“any”。我们如何在Typescript中为这些对象指定适当的类型?除非在绝对必要的情况下,否则您不想使用
任何
any
意味着一个类型可以是任何东西,因此您不知道该类型是什么。Typescript无法检查变量是否被滥用,因为您已经说过“一切正常”
有很多方法可以正确地键入,但这里有一个想法。您可以定义类型颜色
,它是所有有效颜色的字符串
名称的并集。您的private colors
是这些颜色的数组,因此它应该是Color[]
。您的public colorValues
是颜色到数字的映射,因此您可以使用内置实用程序类型将其描述为Record
,这是一个对象,其中键为typeColor
,值为typenumber
。(如果对象中不存在所有颜色,则将使用Partial
进行不完整映射)
正如其他人所提到的,在TypeScript中使用
any
作为类型注释无助于编写安全代码。在这种情况下,最好不要编写任何类型注释,而是让TypeScript推断类型
如果希望为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
);
}
}
完全移除它,让TS推断它。我的TS代码中没有任何
any
,我几乎想不出任何有效的any
用例可以通过我的代码审查。@Aquarius_Girl让typescript推断它比any
好得多。不惜一切代价避免任何!设置一个特定的类型,如{grey:number;white:number;}
是可以的,但不是必需的。“为什么这是一个问题?”---人们选择TS的原因是编写类型安全的代码。使用any
会使它再次变得不安全。如果你真的想写“安全”的代码,那么有TS有什么意义呢。@Aquarius\u Girl。您可以创建一个接口,如interface Colors{grey:number;white:number;}
,然后为变量提供一个类型注释,如public colorValues:Colors{grey:8,white:9}
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
}
}
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
);
}
}
interface Colors {
grey: number;
white: number;
}
public colorValues: Colors = {
grey: 8,
white: 9
}