是否有可能实现以下接口:打字稿类是功能,而且还具有性能
export interface Foo {
(): void;
bar: number;
}
使用类?
这是我能想出最接近的事:
var foo = function() { } as Foo;
foo.bar = 5;
是否有可能实现以下接口:打字稿类是功能,而且还具有性能
export interface Foo {
(): void;
bar: number;
}
使用类?
这是我能想出最接近的事:
var foo = function() { } as Foo;
foo.bar = 5;
虽然我不能完全肯定,我觉得这个使用类,而一些严重的黑客是不可能的。我认为这种接口语法实际上是为了支持外部库类型,在许多情况下这种结构存在。
你在示例代码中实际引用的是static
类的成员。我的意思是一个具有公共构造函数的类,一些静态成员正是这种构造。但静态成员不能在接口中声明(显然)。
所有类都是编译为js时的函数。
export class FooClass implements Foo {
bar: number;
constructor() {
this.bar = 1;
}
}
你不能有一类这样做,但你可以使用类型别名和路口类型做这样的事情:
// Define the type of your objects
type Foo = {(): void } & { bar: number };
// You could have a factory method to create instances
var fooFactoryMethod = (func:() => void, bar: number) => {
var foo = func as Foo;
foo.bar = bar;
return foo;
}
var myObject = fooFactoryMethod(() => { console.log("Hello world") }, 23)
// Or just creating them manually
var myObject2 = (() => { console.log("Hello world") }) as Foo;
myObject2.bar = 45;
// Now you can use it like this
var func = (arg: Foo) => {
arg();
arg.bar = 34;
}
func(myObject)
尽管模块行为不同于类。 – user3233089
@ user3233089当然,但你需要在这里上课吗?你的用例是什么? – Alex
我需要使用类特定的属性:例如创建多个实例。 – user3233089
确定什么是最好的方法可能的是尝试一下。 –
如果你考虑这个问题..这是一个类被编译到;)另外。该手册是一个非常好的地方来搜索这些问题。 – toskv
在我的回答中,我假定你真正想要的是实现该接口的某个对象,而不一定是一个类。那是对的吗? – Alex