TypeScript - 类型别名

本文介绍了类型别名在编程中的概念,虽然主要用于简化类型名称,如将`string`重命名为`str`,但在联合类型中提供便利。主要展示了如何使用`type`关键字进行定义,并通过实例说明其使用规则。

类型别名是个啥东西

类型别名,顾名思义,就是给类型起个别名。
例如 字符串类型string , 你突然感觉string 这个单词太长了,竟然有6个字母,
你就想让string 叫 str ,才3个字母,多么的简洁。
好,满足你,类型别名来帮你实现。

类型别名能干啥

说实话,类型别名除了能帮你起个名之外,也没啥其他的作用。
当然了,在给联合类型起别名的时候,还是能感觉出来方便的,毕竟变短了嘛。
就是你可以不用它,但ts不能没有这个功能。

类型别名的定义语法

用 type. 来定义别名,格式如下:
type 新类型名 = 原来的类型名;

写个例子吧

// 用 type 来定义
type nb = number | boolean;
let a : nb = 123;
a = true;
// a = '123';// 错误,只支持 number 和 boolean
import globals from "globals"; import pluginJs from "@eslint/js"; import tseslint from "typescript-eslint"; import pluginReact from "eslint-plugin-react"; /** @type {import('eslint').Linter.Config[]} */ export default [ { files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"] }, { languageOptions: { globals: { ...globals.browser, ...globals.node } } }, pluginJs.configs.recommended, ...tseslint.configs.recommended, pluginReact.configs.flat.recommended, { rules: { // eslint (http://eslint.cn/docs/rules) "no-var": "error", // 要求使用 let 或 const 而不是 var "no-multiple-empty-lines": ["error", { max: 1 }], // 不允许多个空行 "no-use-before-define": "off", // 禁止在 函数/类/变量 定义之前使用它们 "prefer-const": "off", // 此规则旨在标记使用 let 关键字声明但在初始分配后从未重新分配的变量,要求使用 const "no-irregular-whitespace": "off", // 禁止不规则的空白 "no-unexpected-multiline": "error", // 禁止空余的多行 "no-useless-escape": "off", // 禁止不必要的转义字符 // react "react/prop-types": "off", // 使用 TypeScript 或其他类型检查工具,可以关闭此规则,因为可能已经有更好的类型检查机制。 "react/react-in-jsx-scope": "off", // 如果你使用 React 17 及以上,不需要在每个文件中导入 React,可关闭此规则。 "react/display-name": "warn", // 对组件缺少 displayName 属性发出警告,有助于调试和性能分析。 // typeScript (https://typescript-eslint.io/rules) "@typescript-eslint/no-unused-vars": "error", // 禁止定义未使用的变量 "@typescript-eslint/prefer-ts-expect-error": "error", // 禁止使用 @ts-ignore "@typescript-eslint/no-inferrable-types": "off", // 可以轻松推断的显式类型可能会增加不必要的冗长 "@typescript-eslint/no-namespace": "off", // 禁止使用自定义 TypeScript 模块和命名空间。 "@typescript-eslint/no-explicit-any": "off", // 禁止使用 any 类型 "@typescript-eslint/ban-types": "off", // 禁止使用特定类型 "@typescript-eslint/explicit-function-return-type": "off", // 不允许对初始化为数字、字符串或布尔值的变量或参数进行显式类型声明 "@typescript-eslint/no-var-requires": "off", // 不允许在 import 语句中使用 require 语句 "@typescript-eslint/no-empty-function": "off", // 禁止空函数 "@typescript-eslint/no-use-before-define": "off", // 禁止在变量定义之前使用它们 "@typescript-eslint/ban-ts-comment": "off", // 禁止 @ts-<directive> 使用注释或要求在指令后进行描述 "@typescript-eslint/no-non-null-assertion": "off", // 不允许使用后缀运算符的非空断言(!) "@typescript-eslint/explicit-module-boundary-types": "off", // 要求导出函数和类的公共类方法的显式返回和参数类型 } } ]; 代码优化扩展,添加注释
05-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值