首页 > 解决方案 > 使用其他类型作为变量创建复合类型

问题描述

让我们假设我有以下类型(只是一个例子来说明我的观点):

type Alignment =
  "top left" |
  "middle left" |
  "bottom left" |
  "top center" |
  "middle center" |
  "bottom center" |
  "top right" |
  "middle right" | 
  "bottom right";

有可能做这样的事情吗?

type Vertical = "top" | "middle" | "bottom";
type Horizontal = "left" | "center" | "right";
type Alignment = `${Vertical} ${Horizontal}`;

编辑所以我看到我的问题已经过时了,根本不是关于打字稿的,抱歉,但感谢您的回答,真的很有帮助。

无论如何,我在 VSCode 中遇到了这个错误,知道吗?

解析错误:键入 expected.eslint

标签: typescript

解决方案


是的,从 Typescript 4.1 版开始就有可能!

您可以在此处阅读有关模板文字类型的信息 - https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html

Here's your code in the Typescript playground where you can hover on the Alignmenttype to see what it looks like: https://www.typescriptlang.org/play?#code/C4TwDgpgBAahBOwCWBjAhgGygXigImAHsw8oAffAWyQBMaMJSK8AjQ4IyvAbgChRIUABKF4SAF6EAdsEw58DAGbAm+FBBkJVeMQHMAFir4DoAQQxJdUyhuDyABgBIA3nESpMAXyguRYyTJe9txAA


推荐阅读