数据结构的类型接口

问题描述

运行此代码片段后,我将以下数据结构打印到控制台

let editorDelta: DeltaStatic | undefined = editor?.getContents()
console.log(editorDelta)

控制台:

ops: [
  {
    attributes: {
      underline: true,italic: true,color: "#000fff",background: "#fff000",bold: true
    },insert: "this"
  },{
    attributes: {
      underline: true,insert: "that"
  },]

我正在尝试为此数据创建类型变量,但遇到了一些问题。下面的接口正在工作,但我想为一些更嵌套的数据(如属性和插入 ext)定义类型。

interface DeltaStatic {
    ops?: object[]
}

我尝试过但不起作用的其他一些示例。

interface DeltaStatic {
  ops?: {
    attributes: {
      underline: boolean,italic: boolean,color: string,background: string,bold: boolean
    },insert: string
  }[] 
}
    
interface DeltaStatic {
  ops?: [
    {
      attributes: {
        underline: boolean,bold: boolean
      },insert: string
    }
  ] 
}

解决方法

界面通常描述对象的形状。假设 editorDelta 是一个具有唯一属性 ops 的对象,它具有您所描述的对象数组,这将:

interface DeltaStatic {
  ops: {
    attributes: {
      underline: boolean;
      italic: boolean;
      color: string;
      background: string;
      bold: boolean;
    };
    insert: string;
  }[];
}

请记住,接口使用 ; 来表示项目的结尾,而不是 ,

,
type DeltaOperation = { insert?: any,delete?: number,retain?: number } & OptionalAttributes;

interface StringMap {
    [key: string]: any;
}

interface OptionalAttributes {
    attributes?: StringMap;
}

interface DeltaStatic {
    ops?: DeltaOperation[];
    retain(length: number,attributes?: StringMap): DeltaStatic;
    delete(length: number): DeltaStatic;
    filter(predicate: (op: DeltaOperation) => boolean): DeltaOperation[];
    forEach(predicate: (op: DeltaOperation) => void): void;
    insert(text: any,attributes?: StringMap): DeltaStatic;
    map<T>(predicate: (op: DeltaOperation) => T): T[];
    partition(predicate: (op: DeltaOperation) => boolean): [DeltaOperation[],DeltaOperation[]];
    reduce<T>(predicate: (acc: T,curr: DeltaOperation,idx: number,arr: DeltaOperation[]) => T,initial: T): T;
    chop(): DeltaStatic;
    length(): number;
    slice(start?: number,end?: number): DeltaStatic;
    compose(other: DeltaStatic): DeltaStatic;
    concat(other: DeltaStatic): DeltaStatic;
    diff(other: DeltaStatic,index?: number): DeltaStatic;
    eachLine(predicate: (line: DeltaStatic,attributes: StringMap,idx: number) => any,newline?: string): DeltaStatic;
    transform(index: number,priority?: boolean): number;
    transform(other: DeltaStatic,priority: boolean): DeltaStatic;
    transformPosition(index: number,priority?: boolean): number;
}