如何定义一个类型,该类型是从字符串中排除“ a”的类型?

时间:2018-10-15 10:59:41

标签: typescript types

我想定义一个这样的类型:

type Response = {
   type: 'a',
   value: string
} | {
   type: ???, // any other string except 'a'
   value: number
}

有可能吗?

我尝试过:

type OtherStrings = Exclude<string, 'a'>

但是它没有按我预期的那样工作。

1 个答案:

答案 0 :(得分:2)

我想没有什么比这可能的更好了

type OtherStrings<T> = T extends 'a' ? never : string

const OtherStrings: OtherStrings<'b'> = 'b'
const OtherStrings: OtherStrings<'a'> = 'a' // err

PS。您应该明确列出要允许或不允许的所有可能的字符串选项,而不是像这样的骇客。

相关问题