Javascript Typescript:将属性设置为特定类型

Javascript Typescript:将属性设置为特定类型,javascript,typescript,Javascript,Typescript,我对Typescript非常陌生,只是在探索如何转换现有的JS代码。我的方法(很可能有缺陷)是尽可能少地让它在TypeScript中工作,然后逐渐将其转换为遵循“最佳实践” 我似乎在第一关就摔倒了 我使用jQuery(在ASP.NET.NET5应用程序中)编写了以下类型的脚本 因此,当页面加载时,将执行something.init。这将通过jQuery选择器设置事件处理程序等。所有这部分似乎都工作得很好 然而 在某个时刻,一个事件处理程序将启动,我将创建一个新的对象来实现MyInterface。

我对Typescript非常陌生,只是在探索如何转换现有的JS代码。我的方法(很可能有缺陷)是尽可能少地让它在TypeScript中工作,然后逐渐将其转换为遵循“最佳实践”

我似乎在第一关就摔倒了

我使用jQuery(在ASP.NET.NET5应用程序中)编写了以下类型的脚本

因此,当页面加载时,将执行
something.init
。这将通过jQuery选择器设置事件处理程序等。所有这部分似乎都工作得很好

然而

在某个时刻,一个事件处理程序将启动,我将创建一个新的对象来实现
MyInterface
。我需要保留它(通过将它设置为属性/字段
currentThing
)的值),以便以后的事件可以访问它

但是,Typescript不喜欢行
currentActivity:MyInterface,
,我得到了错误:

“MyInterface”仅引用类型,但在此处用作值


我建议您使用新界面键入
something
对象:


对象遵循键值结构,Typescript将当前对象定义理解为

const something={
//关键值
当前事物:MyInterface,
};
由于
MyInterface
不是有效值,它将抛出上述错误

在这种情况下,您应该为
something
对象定义类型,键入其属性,如下所示:

接口MyInterface{
prop1:字符串;
建议2:数字;
}
接口某物接口{
当前事物:MyInterface;
初始化:()=>void
}
const currentThing={prop1:'aStringValue',prop2:12345};
const something:something接口={
现在的事情,,
init:():void=>{
//
}
};
$(something.init);

正如其他人所说,不能对对象文本中的字段使用键入。如果有必要,我可以使用类来提高可读性,并使用该类的实例导出常量

例如:

interface MyInterface {
    prop1: string;
    prop2: number;
}

class Something implements MyInterface {

    public Something(public prop1: string, public prop2: number) {
    }

    init(): void {
    }
}

export const something = new Something('value1', 10);

$(something.init);

不能将类型指定给对象文字内的属性。您需要为
something
对象分配一个类型,例如
constsomething:{currentThing:MyInterface,init:()=>void}={/*…*/}
。提取该接口也可能是一个好主意。我想知道我的改编是否被视为良好的实践。。。我从
const currentThing={prop1:'aStringValue',prop2:12345}更改
常量currentThing:MyInterface=null因为我不喜欢创建虚拟对象。我也不确定这是否应该是一个
常量
。。。在
init
函数中,我可以使用
something.currentThing={prop1:“abc”,prop2:12345}设置它并稍后检索。您是否考虑过使用
?例如,您可以将
init()
替换为
constructor()
,然后调用
$(newsomething(currentThing))
interface MyInterface {
    prop1: string;
    prop2: number;
}

interface Something {
  currentThing: MyInterface;
  init: () => void;
}

const something: Something = {
    currentThing: {
      prop1: 'foo',
      prop2: 5,
    },

    init: (): void => {
        //
    },
};

console.log(something.init);
interface MyInterface {
    prop1: string;
    prop2: number;
}

class Something implements MyInterface {

    public Something(public prop1: string, public prop2: number) {
    }

    init(): void {
    }
}

export const something = new Something('value1', 10);

$(something.init);