我想创建一个类型谓词,以便当我在泛型的Union数组上使用filter
时,它将返回正确的类型.
我编写了一个类型来指示相应id的转换函数的输入/输出类型:
type ConverterGroupIdToFunc = {
text: [string, string]
image: [File, string]
}
type ConverterGroupId = keyof ConverterGroupIdToFunc
type ConverterGroup<T extends ConverterGroupId> = {
id: T
convertFunc: (s: ConverterGroupIdToFunc[T][0]) => (ConverterGroupIdToFunc[T][1]);
}
我还需要一个ConverterGroup数组来存储2种不同类型的泛型(ConverterGroup<"text">|ConverterGroup<"image">)[]
type ConverterGroupUnion = ConverterGroup<"text"> | ConverterGroup<"image">
对于converterGroups: (ConverterGroup<"text">|ConverterGroup<"image">)[]
,如果转换器组的id
也是"text"
,我希望find()
返回类型ConverterGroup<"text">
.
我试图使用一个类型谓词告诉find()
返回正确的类型,但找不到方法:
function isConverterGroup<T extends ConverterGroupId>(converterGroupId: T) {
return (converterGroup: ConverterGroupUnion): converterGroup is ConverterGroup<T> => {
return converterGroup.id === converterGroupId;
}
}
const convertFunc = converterGroups.find(isConverterGroup("text"))!.convertFunc;
上面的代码给了我一个错误:
A type predicate's type must be assignable to its parameter's type.
Type 'ConverterGroup<T>' is not assignable to type 'ConverterGroupUnion'.
Type 'ConverterGroup<T>' is not assignable to type 'ConverterGroup<"text">'.
Types of property 'id' are incompatible.
Type 'T' is not assignable to type '"text"'.ts(2677)