網站搜尋

既是函數又有屬性的 Typescript 類別


是否可以實作以下介面:

export interface Foo {
    (): void;

    bar: number;
}

使用類別嗎?

這是我能想到的最接近的東西:

var foo = function () { } as Foo;

foo.bar = 5;

答案#1

雖然我不完全確定,但我認為使用類別在不進行一些嚴重修改的情況下是不可能的。我認為這個介面語法其實是用來支持外部庫的型別定義,在很多情況下這種構造是存在的。

你在範例程式中實際上指的是類別的 static 成員。我的意思是,一個有公共建構函式和一些靜態成員的類正是這種結構。但靜態成員不能在介面中宣告(這很明顯)。

答案#2

你不能讓一個類這樣做,但你可以使用類型別名和交叉類型來做類似的事情:

// 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)

遊樂場