Typescript:如何描述特定的对象接口?

时间:2018-09-29 16:28:12

标签: typescript

我有一个这样的对象结构:

{
  someKey: number,
  // list of string keys which may be missing
  [key: string]: string
}

所以我将其描述为:

interface IStringHash {
    [key: string]: string
}

interface ISomeObjectStructure {
    someKey: number
 }

const SomeFunction = (hash: ISomeObjectStructure & IStringHash): any => {
    return '';
}

const data = {
   someKey: 1,
   a: 'Hello',
   b: 'world'
}
SomeFunction(data);
             ^^^^

const data1 = {someKey: 1}

SomeFunction(data1);
             ^^^^

但出现错误:

Argument of type '{ someKey: number; a: string; b: string; }' is not assignable to parameter of type 'ISomeObjectStructure & IStringHash'. Type '{ someKey: number; a: string; b: string; }' is not assignable to type 'IStringHash'. Property 'someKey' is incompatible with index signature. Type 'number' is not assignable to type 'string'. const data: { someKey: number; a: string; b: string; }

typescript playground

怎么了?

如何描述这样的复杂对象?

答案:typescript playground

0 个答案:

没有答案