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
164 views
in Technique[技术] by (71.8m points)

javascript - Typescript: why function without parameters can be cast to function with parameters

Why there aren't any compilation errors in this code? Code:

function partial(f: (a: string) => string, a: string) : string {
  return "";
}

var test = () => "";
var result = partial(test, "");

Function "partial" takes as the first argument a function, that takes one parameter, but I pass to it function, that doesn't take any parameters, and typescript compiler thinks, that this is OK. I understand that this can't break anything because you can pass all parameters in the world to the function that doesn't take any, and it won't break anything, but it should be a compilation error because typescript is about types and there is an obvious type missmatch and it can possible be a developer's error.

Is there any workarounds for this problem?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

there is an obvious type missmatch and it can possible be a developer's error.

There's nothing obviously wrong with this code. Consider something like this:

let items = [1, 2, 3];
// Print each item in the array
items.forEach(item => console.log(item));

Is this code correct? Definitely! But forEach invokes its provided function with three arguments, not one. It would be tedious to have to write:

items.forEach((item, unused1, unused2) => console.log(item));

Note that you can still get errors if you try to do something that's actually wrong. For example:

function printNumber(x: number) { console.log(x); }
let strings = ['hello', 'world'];
strings.forEach(printNumber); // Error, can't convert string to number

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

...