【发布时间】:2021-05-31 10:31:13
【问题描述】:
有没有办法让 typescript 为以下内容显示类型提示?
我正在尝试在输入“test”时显示“test1”或“test2”类型,但我失败了。
type A = "test1" | "test2" | string
// update 1: it does show 'test1' & 'test2' but not in the 'constant' category (e.g. menuItem/spanner/wrench icon ), but in 'string' category (e.g. 'abc' icon )
// <--- doesn't show 'test1' or 'test2' when i am typing 'test'
const a : A = 'test1'
在示例 1 中,type A 在字符串中更宽,因此我们将 'test1'/'test2' 的类型定义丢失为字符串文字
理想情况下,变量 a 仍应显示 'test1' 和 'test2' 用于自动完成,如示例 2 中的 bvariable。
示例 1:
示例 2:
【问题讨论】:
-
你可以这样做:
type A = 'test1' | 'test2' | Omit<string, 'test1' | 'test2'>来保留 A 的类型吗? -
✨神奇,它有效!请张贴作为答案,所以我可以接受。如果你能给出一个简短的描述它是如何工作的,那就更好了,但没有它仍然很棒。
-
嗯,接受的答案有效,但根本不是因为它所说的原因;
Omit<string, 'test1' | 'test2'>并不意味着“任何string除了"test1"或"test2";如果它意味着什么,它意味着“任何string没有名为test1或test2的已知属性”,即...奇怪。在microsoft/TypeScript#29729 GitHub 上有一个关于此的官方问题,我已经提交了一个答案来解释这里发生了什么。
标签: typescript