javascript - 在 Typescript 中什麼是 `export type`?
我注意到 Typescript 中有以下語法。
export type feline = typeof cat;
據我所知,type 不是內建的基本類型,也不是介面或類別。實際上它看起來更像是用於別名的語法,但我找不到參考資料來驗證我的猜測。
那麼上述陳述意味著什麼?
答案#1
這是一個 型別別名 - 它用來給型別另一個名稱。
(在這裡比較 type 與 interface)
在你的例子中,feline 將會是 cat 所屬的類型。
這裡有一個更完整的例子:
interface Animal {
legs: number;
}
const cat: Animal = { legs: 4 };
export type feline = typeof cat;
feline 將會是 Animal 類型,你可以在任何你想使用的地方當作類型使用。
const someFunc = (cat: feline) => {
doSomething(cat.legs);
};
export 只是將它從檔案中匯出。這與這樣做是相同的:
type feline = typeof cat;
export {
feline
};
