簡體   English   中英

如何在Typescript中的泛型對象接口中描述?

[英]How to describe in generics object interface in Typescript?

我有這樣的對象:

{
  classNames: {
    foo: 'foo',
    ....
    bar: 'bar'
  },
  method1: () => {....},
  method2: () => {....},
  stringKey1: 'stringKey1',
  ...
  stringKeyN: 'stringKeyN',
}

我需要為函數描述一個函數參數

function func1(myObj) { ... }

我的描述失敗

interface IMyObject {
  classNames: [key: string]: string;
  method1: Function;
  method2: Function;
  [key: string]: string | undefined;
}

錯誤:

  • “[any, string]”類型的屬性“classNames”不可分配給字符串索引類型“string”。
  • “Function”類型的屬性“method1”不可分配給字符串索引類型“string”。
  • “Function”類型的屬性“method2”不可分配給字符串索引類型“string”。

您的問題是由於嘗試在該類型的“異常”旁邊指定索引類型引起的。

如果您查看下面的代碼(這應該是您所追求的) - 如果Example接口具有索引簽名,它將與其他成員發生沖突。 例如method1不符合這個: [index: string]: string;

interface Example {
    classNames: { [index: string]: string; };
    method1: () => void;
    method2: () => void;
}

interface Example1 {
    [index: string]: string;
}

type ExampleUnion = Example | Example1;

const x: ExampleUnion = {
  classNames: {
    foo: 'foo',
    bar: 'bar'
  },
  method1: () => {},
  method2: () => {},
  stringKey1: 'stringKey1',
  stringKeyN: 'stringKeyN',
}

現在這會導致訪問問題,因為這兩個接口仍然存在沖突。 可以用自定義類型保護解決這個問題,但不同的形狀可以一次性解決你的所有問題:

interface Example {
    classNames: { [index: string]: string; };
    propertyBag: { [index: string]: string; };
    method1: () => void;
    method2: () => void;
}

const x: Example = {
  classNames: {
    foo: 'foo',
    bar: 'bar'
  },
  method1: () => {},
    method2: () => { },
    propertyBag: {
        stringKey1: 'stringKey1',
        stringKeyN: 'stringKeyN',
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM