Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript-定义不规则对象结构的类型_Typescript - Fatal编程技术网

Typescript-定义不规则对象结构的类型

Typescript-定义不规则对象结构的类型,typescript,Typescript,我想正确键入具有以下结构的比较器对象: const Comparator: ComparatorType = { string: { equals: function(a: string, b: string) {...}, notEquals: function(a: string, b: string) {...}, contains: function(a: string, b: string) {...} ... }, number: {

我想正确键入具有以下结构的
比较器
对象:

const Comparator: ComparatorType = {
  string: {
    equals: function(a: string, b: string) {...},
    notEquals: function(a: string, b: string) {...},
    contains: function(a: string, b: string) {...}
    ...

  },
  number: {
    equals: function(a: number, b: number) {...},
    lowerThan: function(a: number, b: number) {...},
    greaterThan: function(a: number, b: number) {...}
    ...
  },
  datetime: {...}
}
因此,正如您所看到的,一些函数对于多种数据类型是通用的(如
equal
),但其他函数是唯一的。我能够想出:

type DataType = "string" | "integer" | "datetime"
type Operation = "equals" | "notEquals" | "contains" | "notContains" | ...

// and define functions:
type CompareStringCommonFunc = (
  a: string,
  b: string
) => boolean

type CompareIntegerCommonFunc = (
  a: number,
  b: number
) => boolean

...others...
因此,我最终可以得出这样的
ComparatorType

type ComparatorType = {
  [dataType in DataType]: {
    [funcName in Operation]:
      | CompareStringCommonFunc
      | CompareStringInFunc
      | CompareStringBetweenFunc
      | CompareIntegerCommonFunc
      | CompareIntegerBetweenFunc
      | CompareIntegerInFunc
  }
}

但是它显然不起作用,因为
比较器
是不规则的(我的意思是每个
数据类型
都没有所有的
操作
s),而且我的typescript知识还不太深,我自己还没有弄清楚。我如何解决它,以便我可以为
string
数据类型
分配一些具有特定函数的
操作
值。尝试将类型和值“映射”到更复杂的结构会使事情变得复杂,特别是当每个“类型”的函数名称、数字和类型都不同时。您可以更明确地定义您的
ComparatorType

type CompareFn<T> = (a: T, b: T) => void;

type ComparatorType = {
    string: {
        equals: CompareFn<string>,
        notEquals: CompareFn<string>,
        contains: CompareFn<string>
    },
    number: {
        equals: CompareFn<number>,
        lowerThan: CompareFn<number>,
        greaterThan: CompareFn<number>
    },
    // etc
}
type CompareFn=(a:T,b:T)=>void;
类型比较器类型={
字符串:{
等于:比较n,
注:比较,
包含:CompareFn
},
编号:{
等于:比较n,
洛厄坦:比较,
大于:比较
},
//等
}
这里,
CompareFn
只是一个通用的实用程序类型,用于简化函数类型的定义,这些函数类型似乎都有相同的参数模式,只是类型不同而已

如果需要,您仍然可以使用类型
DataType
,方法是反向工程此类型的键:
type DataType=keyof ComparatorType。然而,反向工程一般的
操作
类型更为困难,因为在
比较类型
的“类型”之间,键
等于
notEquals
等不一致。但是您仍然可以使用类似于
keyof ComparatorType['string']
keyof ComparatorType['number']
等的方法轻松获取与特定类型相关联的键