Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

typescript - Validate interface of function call

I have a the following code:

myArray: { value: string; name: string; }[]; 

orderFunction (a, b) {
    if (a.wrong > b.wrong) {
        return 1;
    } else {
        return -1;
    }
}

myArray.sort(orderFuncion);

The above code should give an error as the elements in the array don't have the wrong property, but it does not

The definition of sort is correct:

/**
  * Sorts an array.
  * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.
  */
sort(compareFn?: (a: T, b: T) => number): this;

but orderFunction is typed as (any any)

How can I make typescript validate it automatically ?

question from:https://stackoverflow.com/questions/65916641/validate-interface-of-function-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the paramaters a and b are both typed any because you haven't annotated them with a type.

orderFunction (a: { value: string; name: string; }, b: { value: string; name: string; }) {
    if (a.wrong > b.wrong) {
        return 1;
    } else {
        return -1;
    }
}

or in a generic way

orderFunction<T> (a: T, b: T) {
    if (a.wrong > b.wrong) {
        return 1;
    } else {
        return -1;
    }
}

will give you the desired error because the type { value: string; name: string; } does not have a wrong property.

If you don't want implicit any to be a thing you can set noImplicitAny: true in your tsconfig.json.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...