TypeScript 是否允许类型别名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21839692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does TypeScript allow type aliases?
提问by Trident D'Gao
So I wish I could use an alias to an ugly type that looks like this:
所以我希望我可以为一个看起来像这样的丑陋类型使用别名:
Maybe<Promise<Paged<Carrier>, Problem>>[]
Something like:
就像是:
import Response = Maybe<Promise<Paged<Carrier>, Problem>>[];
Is there a way to do type aliases in TypeScript?
有没有办法在 TypeScript 中做类型别名?
回答by Mariusz Pawelski
From version 1.4 Typescript supports type aliases (source).
从 1.4 版开始,Typescript 支持类型别名(source)。
Type Aliases
You can now define an alias for a type using the type keyword:
type PrimitiveArray = Array<string|number|boolean>; type MyNumber = number; type NgScope = ng.IScope; type Callback = () => void;
Type aliases are exactly the same as their original types; they are simply alternative names.
类型别名
您现在可以使用 type 关键字为类型定义别名:
type PrimitiveArray = Array<string|number|boolean>; type MyNumber = number; type NgScope = ng.IScope; type Callback = () => void;
类型别名与其原始类型完全相同;它们只是替代名称。
And from version 1.6 Typescript supports generic type aliases (source).
从 1.6 版开始,Typescript 支持泛型类型别名(source)。
Generic type aliases
Leading up to TypeScript 1.6, type aliases were restricted to being simple aliases that shortened long type names. Unfortunately, without being able to make these generic, they had limited use. We now allow type aliases to be generic, giving them full expressive capability.
type switcharoo<T, U> = (u: U, t:T)=>T; var f: switcharoo<number, string>; f("bob", 4);
通用类型别名
在 TypeScript 1.6 之前,类型别名被限制为缩短长类型名称的简单别名。不幸的是,由于无法使这些通用,它们的用途有限。我们现在允许类型别名是通用的,赋予它们完整的表达能力。
type switcharoo<T, U> = (u: U, t:T)=>T; var f: switcharoo<number, string>; f("bob", 4);
回答by TSV
TypeScript supports imports, e.g.:
TypeScript 支持导入,例如:
module A {
export class c {
d: any;
}
}
module B {
import moduleA = A;
var e: moduleA.c = new moduleA.c();
}
module B2 {
import Ac = A.c;
var e: Ac = new Ac();
}
Update 1
更新 1
Since TS 1.4 we can use type declarations:
从 TS 1.4 开始,我们可以使用类型声明:
type MyHandler = (myArgument: string) => void;
var handler: MyHandler;
Since TS 1.6 we can use local type declarations:
从 TS 1.6 开始,我们可以使用本地类型声明:
function f() {
if (true) {
interface T { x: number }
let v: T;
v.x = 5;
}
else {
interface T { x: string }
let v: T;
v.x = "hello";
}
}
回答by Martin Jambon
A poor man's solution is to declare a dummy variable (e.g. t
) with the desired type and use typeof t
instead of the long type expression:
一个穷人的解决方案是声明一个t
具有所需类型的虚拟变量(例如)并使用typeof t
而不是长类型表达式:
var t: { (x: number, f: { (foo: string, bar:boolean): void }): void }; var f: typeof t; var g: typeof t;