Typescript中的`export type`是什么?


77

我在Typescript中注意到以下语法。

export type feline = typeof cat;

据我所知,type它不是内置的基本类型,也不是接口或类。实际上,它看起来更像是别名的语法,但是我找不到参考来验证我的猜测。

那么上面的陈述是什么意思呢?

Answers:


94

这是类型别名-用于为类型赋予其他名称。

在您的示例中,feline将是任何类型cat

这是更完整的示例:

interface Animal {
    legs: number;
}

const cat: Animal = { legs: 4 };

export type feline = typeof cat;

feline将是type Animal,您可以在任何地方将其用作类型。

const someFunc = (cat: feline) => {
    doSomething();
};

export只需从文件中导出即可。与此相同:

type feline = typeof cat;

export {
    feline
};

最简单的示例是字符串文字类型:type Easing = "ease-in" | "ease-out" | "ease-in-out";
Boris Yakubchik

13
我无法深入了解。那么接口和类型之间有什么区别?类型主要用于什么?
Ashfaque Rifaye


我也通过链接,但仍不完全清楚。
Kapil Raghuwanshi

@KapilRaghuwanshi微软以为有人可能会感到困惑,并写了一段关于他们之间差异的文章。就像他们说的那样,经验法则可能是“只要有可能,请优先选择接口而不是类型”。
TechNyquist
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.