Typescript-对于传递给用户定义类的函数的构造函数参数,不检查方法参数的类型

时间:2019-04-22 16:29:41

标签: typescript

在以下代码的上下文中,如果函数runner收到一个 构造函数类型的参数,并且构造函数返回用户定义的类,如果传递给runner函数的构造函数用于具有方法run且该类没有参数的类,则打字稿语言服务器不会抱怨与运行程序声明中指定的参数类型匹配。但是语言服务器会抱怨方法是否采用原始类型作为参数。

我通过了typescriptlang的常见问题解答。我知道我们 可以为一个函数参数传递一个带有较少参数的函数。但是在这种情况下,允许类型不匹配。

// I Know usually the run method of a thread doesn't contain a parameter
// But used anyway for demonstrating the problem
class Player {

}

function runner(threadClass: { new(): { run(thisParameterIsNotBeingCheckdIfItIsAUserDefinedClass: Player): void } }) {
    new threadClass(); // not important
}   

class Thread {
    run(ThisMethodShouldBreakTheContractOfTheRunMethodSpecifedInRunner
        : string){

    }
}


runner(Thread); // Should Complain That the Thread Class is not 
                // compatible. But it is not happening.

在代码的上下文中,runner函数调用应抱怨说Thread类不包含匹配的run方法。 可以通过将以上代码粘贴到VS Code中来复制。谢谢您的时间:)。

0 个答案:

没有答案