TypeScript 是否允许类型别名? [英] Does TypeScript allow type aliases?

查看:31
本文介绍了TypeScript 是否允许类型别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我希望我可以为一个看起来像这样的丑陋类型使用别名:

So I wish I could use an alias to an ugly type that looks like this:

Maybe<Promise<Paged<Carrier>, Problem>>[]

类似于:

import Response = Maybe<Promise<Paged<Carrier>, Problem>>[];

有没有办法在 TypeScript 中做类型别名?

Is there a way to do type aliases in TypeScript?

推荐答案

Typescript 从 1.4 版开始支持类型别名 ().

From version 1.4 Typescript supports type aliases (source).

输入别名

您现在可以使用 type 关键字为类型定义别名:

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.

从 1.6 版开始,Typescript 支持泛型类型别名 (来源).

And from version 1.6 Typescript supports generic type aliases (source).

通用类型别名

直到 TypeScript 1.6,类型别名被限制为缩短长类型名称的简单别名.不幸的是,由于无法使这些通用,它们的用途有限.我们现在允许类型别名是通用的,赋予它们完整的表达能力.

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 是否允许类型别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆