Typescript interface problem

interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function (start: number) { };
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

Why does the above API specify that the counter function returns string, but in fact, the counter function does not return, and does not report an error

interface Counter {
    (start: number): void;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function (start: number) { return "12"};
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

but I swapped the interface and function return and reported an error

Jan.18,2022

you added < Counter > here, of course. This means that you have clearly thought that the following function (start: number) {return '12'}; conforms to the type constraint of the function. If you remove it here, there will be a corresponding error prompt.

I guess you borrowed the syntax of other static languages? For example, java, can be regarded as a trap here. Typescript does not have the concept of forced transformation, so it is normal that there are no mistakes.

Menu