我是 Typescript 的新手,只是探索如何转换我们现有的 JS 代码。我的方法(这很可能有缺陷)是做最少的工作,让它在 TypeScript 中工作,然后逐渐将其转换为遵循“最佳实践”。
我好像在第一关就倒下了......
我有以下 TypeScript,使用 jQuery(在 ASP.NET .NET5 应用程序中)。
interface MyInterface {
prop1: string;
prop2: number;
}
const something = {
currentThing : MyInterface,
init: (): void => {
//
}
};
$(something.init);
所以想法是当页面加载时,something.init
将被执行。这将设置诸如事件处理程序之类的东西通过 jQuery 选择器,等等。 等等。所有这些部分似乎都工作得很好。
然而...
在某个时候,事件处理程序将被触发,我将创建一个将实现 MyInterface
的新对象。我需要保留它(通过将它设置为属性/字段 currentThing
的值),以便以后的事件可以访问它。
但是,Typescript 不喜欢 currentActivity: MyInterface,
这行,我得到了错误:
'MyInterface' only refers to a type, but is being used as a value here.
最佳答案
一个对象遵循key-value结构,Typescript将当前对象定义理解为
const something = {
// key value
currentThing : MyInterface,
};
并且由于 MyInterface
不是有效值,它会抛出上述错误。
在这种情况下,您应该做的是为 something
对象定义类型,键入其属性,如下所示:
interface MyInterface {
prop1: string;
prop2: number;
}
interface SomethingInterface {
currentThing : MyInterface;
init: () => void
}
const currentThing = { prop1: 'aStringValue', prop2: 12345 };
const something: SomethingInterface = {
currentThing,
init: (): void => {
//
}
};
$(something.init);
关于javascript - typescript :将属性设置为特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65232944/