简体   繁体   中英

typescript: enforce strict type checking

Please see the code here

interface IBar {
    search:(any) => void;
}

class test{
    search:(id:string) => void;
    constructor(b:IBar){
        this.search = (id) => this.searchImp(b, id);
    }

    private searchImp (b, id) {
              b.unknownFn(id);
    }
}

using b.unknownFn(id) doesn't give any error. this probably because b inside the function is of type any . still, why can't the typescript compiler infer that, I passed b of type IBar in the call

this.search = (id) => this.searchImp(b, id);

is it to make any javascript work with typescript?

I am porting a JS app to typescript. is there anyway to make the compiler detect these errors (during coding as I may not want to type annotate all function parameter, at least initially as I just copy over the code), so I can correct during compilation. using noImplicitAny detects I used any , still why can't it detect error based on the type passed?

private searchImp (b:IBar, id) {
          b.unknownFn(id);
}

This should get you the red line, unless you specify the type of parameter for your function, it'll be treated as any I believe.

Updated code

Your declaration of searchImp without any argument type annotations is just short-hand for

private searchImp (b : any, id : any) {
          b.unknownFn(id);
}

So you are saying that this method accepts anything for b . No further checks apply to anything of type any .

What you may have in mind is some form of type inference for functions without type annotations. But that is not how TypeScript works -- there is no inference, only implicit type any .

TypeScript type inference does not occur based on usage. It is based on declaration. Eg. both foo and arg are any. However bar takes 1 argument and returns nothing is inferred from declaration.

// declaration
var foo; 
// usage 
foo = 123;
foo = 'asdf';


// declaration
function bar(arg){}
// usage 
bar(123);
bar('asdf');

It appears to me that you have not unchecked the box "Allow implicit 'any' types" in the project's properties under the Typescript tab. This would have given you the red squiggles before even doing what Andreas suggested (adding explicit argument types).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM