首页 > 解决方案 > 如何覆盖 TypeScript 类型别名的 VSCode 工具提示?

问题描述

以下代码不起作用:

type char = 'a' | 'b' | 'c' | 'd' | 'e' | 'f';
const s: string = 'foo';
const [c]: char = s;
// [ERROR]: Type 'string' is not assignable to type 'char'.

我可以这样做:

type char = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | string;

但这会导致两个问题:

  1. 当我将鼠标悬停在一个char变量上时,工具提示说它不是类型stringchar我在 VSCode 中)。我知道我在屏幕截图中没有'a' | 'b' | 'c'etc...,但假装我有,因为工具提示是相同的。

    工具提示

  2. 如果我尝试做类似的事情,我不会收到警告const letter: char = 'notachar'

标签: stringtypescriptvisual-studio-codetypeschar

解决方案


如何覆盖 TypeScript 类型别名的 VSCode 工具提示?

当您有一个可以解析为更简单的联合时,TypeScript 将始终显示更简单的版本

例子:

type char = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | string;
// resolves to the following simpler type so that is what TypeScript will show. 
type char = string;

推荐阅读