通过递归类型减少TypeScript类型的可能性

时间:2019-02-18 08:45:25

标签: typescript typescript-typings

由于TypeScript允许高级类型定义,所以我想尝试这种方法,但这并不像我期望的那么容易。

例如,我想要一种“向导向导”方法:

function fillWizardOptions<T>() {
     return <P extends T> (value:  P) => {
         return fillWizardOptions<Exclude<T, P>>();
     }
}

因此,每次调用链式子功能时,我都想丢失上一个选项,但是目前,Exclude无法正常工作:

fillWizardOptions<string|number|boolean>()
     ('foo')
     ('bar');// Expect here of have only number|boolean, but I still have string|number|boolean

可能我错过了一些事情。

此外,如果有人知道我可以在哪里找到像RegEx101这样的playground

谢谢。

更新:忘记提及我正在使用TypeScript 3.3.1

1 个答案:

答案 0 :(得分:0)

在这种情况下,对于第一个调用,<P>的类型为string,而不是实现'foo'类型。这就是为什么它没有将stringT中排除的原因。因此,如果您写('foo' as string)(<string>'foo')

,它应该可以工作