This question already has answers here:
Is it possible to restrict number to a certain range
                                
                                    (5个答案)
                                
                        
                        
                            Implementing TypeScript interface with bare function signature plus other fields
                                
                                    (3个答案)
                                
                        
                2年前关闭。
            
        

在这里打字新手。我到处搜索过,但似乎找不到答案。

如何定义使该代码有效的结构。这是带有属性的某种功能:

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

最佳答案

可调用对象是具有"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'; }
  }
);

08-18 11:51