我的目标是创建一个以2个字符串数组为参数的函数,并且第二个字符串数组不应包含第一个字符串数组的元素:
function doSomething<
const T extends string,
const K extends StringExcept<T>
>(
firstArray: T[],
secondArray: K[]
) {}
doSomething(['a', 'b'], ['c', 'b']) // 'b' in the second array should cause type error
首先,我想我需要一个像type StringExcept<T>
这样的类型,它应该是这样工作的:
type NotAbc = StringExcept<'abc'>;
const notAbcArray:NotAbc[] = [
'any string', // okay
'123', // okay
'abc' // not allowed
]
我试过的是使用Exclude<>
型,比如Exclude<string, 'abc'>
,但它不是这样工作的,只给出了string
型.此外,我还try 了不同的变体,如T extends K ? never : T
语句,但后来我发现类型排除的功能完全相同
然后我发现了this个问题,说像StringExcept
这样的类型目前在TS中是不可能的(但如果有一些更新,我想知道).我也看了this个实验部分,现在已经关闭了.
那么,有没有办法让我的doSomething(firstArray, secondArray)
发挥作用,不管是不是使用StringExcept
这样的类型?