Is there a type in TypeScript for anything except functions?

后端 未结 4 1310
孤独总比滥情好
孤独总比滥情好 2020-12-01 21:49

I would like to express that a paremeter should be an object or a simple value type (number, bool, string, etc.), but not a function.

If I use Object, t

4条回答
  •  自闭症患者
    2020-12-01 21:56

    With typescript 1.8, you can get pretty close if you define function as something that has all 4 properties: caller, bind, apply and call:

    interface NoCaller {
        caller?: void;
    }
    interface NoBind {
        bind?: void;
    }
    interface NoApply {
        apply?: void;
    }
    interface NoCall {
        call?: void;
    }
    
    type NotAFunction = NoCaller | NoBind | NoApply | NoCall; // if it fails all 4 checks it's a function
    
    
    function check(t: T) {
        // do something
    }
    
    function f() {
    }
    
    class T {
    }
    
    var o = new T();
    
    check({});
    check(o);
    check({caller: 'ok', call: 3, apply: this});
    
    //check(f); // fails
    //check(T); // also fails: classes are functions, you can't really escape from javascript
    

    Surprisingly, the error message is not that bad:

    error TS2345: Argument of type '() => void' is not assignable to parameter of type 'NoCaller | NoBind | NoApply | NoCall'.
      Type '() => void' is not assignable to type 'NoCall'.
        Types of property 'call' are incompatible.
          Type '(thisArg: any, ...argArray: any[]) => any' is not assignable to type 'void'.
    

提交回复
热议问题