问题描述
如何在 TypeScript 中创建构造函数?
看了一堆指南,但语法肯定已经改变了.这是我最近的尝试:
car.d.ts
声明类 Car {构造函数(公共引擎:字符串){this.engine = 引擎 + foo";}}
错误:
不能在环境上下文中调用实现.
通过使用 declare
,您可以定义类类型.类型只是定义的,不应该有实现,所以 declare
需要删除.然后它编译得很好.
class Car {构造函数(公共引擎:字符串){this.engine = 引擎 + "foo";}}
但是该代码编译为:
var Car = (function() {功能汽车(引擎){this.engine = 引擎;this.engine = 引擎 + "foo";}还车;})();
它设置了两次 engine
属性.
这可能不是你想要的,所以 engine
属性应该在类上定义,而不是在构造函数上.
class Car {公共引擎:字符串;构造函数(引擎:字符串){this.engine = 引擎 + "foo";}}
您收到的关于需要 declare
的错误是由于您对定义文件使用了 .d.ts
扩展名.如果您希望文件编译为 JavaScript,扩展名应该只是 .ts
.
编辑 2:
声明类 Car {公共引擎;构造函数(引擎:字符串);}
How do I create a constructor in TypeScript?
Looked at a bunch of guides, but the syntax must've changed. Here's my latest attempt:
car.d.ts
declare class Car {
constructor(public engine: string) {
this.engine = engine + "foo";
}
}
Error:
By using declare
you're defining a class type. The type is only defined, and shouldn't have an implementation, so declare
needs to be removed. Then it compiles fine.
class Car {
constructor(public engine: string) {
this.engine = engine + "foo";
}
}
However that code compiles to:
var Car = (function () {
function Car(engine) {
this.engine = engine;
this.engine = engine + "foo";
}
return Car;
})();
which sets the engine
property twice.
That probably wasn't what you intended, so the engine
property should be defined on the class, not the constructor.
class Car {
public engine: string;
constructor(engine: string) {
this.engine = engine + "foo";
}
}
Edit:
The error you received about needing declare
was due to you using the .d.ts
extension for definition files. The extension should be just .ts
if you want the file to compile to JavaScript.
Edit 2:
declare class Car {
public engine;
constructor(engine: string);
}
这篇关于TypeScript 构造函数 - 环境上下文错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!