TypeScript 是否允许类型别名?

编程入门 行业动态 更新时间:2024-10-08 06:22:24
本文介绍了TypeScript 是否允许类型别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 10:14:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1188570.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:别名   类型   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!