我正在尝试用几个方法构建一个接口,然后根据传入的数据块调用这些方法,这是该对象的关键字之一。
下面是我的类型:
type LogicalFunction<T> = (args: T) => string;
export interface LogicalFunctions
extends Record<string, (args: QueryObject & QueryObject[]) => string> {
$not: LogicalFunction<QueryObject>;
$and: LogicalFunction<QueryObject[]>;
$or: LogicalFunction<QueryObject[]>;
}下面是我正在使用的对象:
export const logicalFunctions: LogicalFunctions = {
$not: (expression: QueryObject) => `NOT(${queryBuilder(expression)})`,
$and: (args: QueryObject[]) => `AND(${queryBuilder(args)})`,
$or: (args: QueryObject[]) => `OR(${queryBuilder(args)})`,
};最后,在我实际调用函数的地方:
if (
key in logicalFunctions
&& (isQueryObject(val) || (val instanceof Array && val.every(v => isQueryObject(v))))
) { logicalFunctions[key](val); }但正如我所写的,我从Typescript编译器得到以下错误:
Argument of type 'QueryObject | QueryObject[]' is not assignable to parameter of type 'QueryObject & QueryObject[]'
我不确定我是不是用某种反模式写的,或者我只是遗漏了什么。任何帮助或指导都将不胜感激:)
发布于 2021-02-08 15:52:12
QueryObject & QueryObject[]意味着参数必须同时是一个QueryObject和一个QueryObjects数组。这很可能是不可能的。
QueryObject | QueryObject[]表示参数可以是QueryObject,也可以是QueryObjects数组。这可能就是你想要的。
在本例中为viewable in Typescript Playground
type T = number | T[]
const t0:T&T[] = [2] // OK
const t1:T&T[] = 2 // NG
type U = number
const u0:U&U[] = [2] // NG
const u1:U&U[] = 2 // NG
const uu0:U|U[] = [2] // OK
const uu1:U|U[] = 2 // OKvariable t0既是T又是T[] (T数组)-只是为了向您展示这样的事情是可能的。t1、u0和u1都是编译错误。
但是,uu0和uu1是可以的。
https://stackoverflow.com/questions/66096287
复制相似问题