如何在Typescript中定义此结构

时间:2018-03-04 17:47:33

标签: javascript typescript

打字稿新手在这里。我到处搜索但似乎无法找到答案。

如何定义使此代码有效的结构。它具有属性的某种功能:

const theThing = createThing(7, 2);
theThing(); // returns a whole number between 1 and 22
theThing.toStringProp();

1 个答案:

答案 0 :(得分:3)

Callables是"bare" or unnamed method signatures的接口:

type ValidNumber = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;

interface Thing {
  (): ValidNumber
  toStringProp(): string
}

构建它们并不完全是类型安全的,所以最好与帮助者一起做一些额外的工作:

interface ThingCallable {
  (): ValidNumber
}

interface ThingProps {
  toStringProp(): string
}

type Thing = ThingCallable & ThingProps;

const thingCallable: ThingCallable = () => 7;
const thingMixin = { toStringProp() { return 'hi' } };
const thing: Thing = Object.assign(thingCallable, thingMixin);

或者,如直接使用Object.assign的重复问题所示:

interface Thing {
  (): ValidNumber
  toStringProp(): string
}

const thing: Thing = Object.assign(
  // Must be a valid () => ValidNumber
  () => 9,
  // Must be a valid superset of the other properties in Thing
  {
    toStringProp() { return 'hello'; }
  }
);