[英]Type declaration is not mandatory in TypeScript generics
我想在TypeScript中询问的问题的简短示例:
export class Test {
public runTest<T>(param: T): T {
return param;
}
}
let test1: Test = new Test();
test1.runTest<string>("string1");
test1.runTest("5555");
这两个“ runTest”语句都将正常执行。 首先要求您传递一个字符串(很棒),其次-并非如此。 但我想强制所有使用“ runTest”的人将某种类型传递给T。
能做到吗 无法找到通过代码完成此操作的方法。 还尝试寻找可能有帮助的TSLint规则,但未找到任何规则。
谢谢
如果您真的想完成此操作(我不必担心为什么要这样做),则需要说服TypeScript在不使用T
情况下推断出一些错误的类型,以免它无法运行考试。 我不知道如何直接执行此操作,但这是一种间接方法:
export class Test {
public runTestIndirectly<T = never>(): (t:T)=>T {
return (t:T)=>t
}
}
因此, runTestIndirectly()
会产生一个功能类似于runTest
的函数。 当您调用runTestIndirectly()
,将推断出T
的类型,该类型无权访问传递给它产生的函数的对象的类型。 而且,如果您将T
default设置为never
,那么如果您忽略将T
指定为有效的内容,则会失败:
let test1: Test = new Test();
test1.runTestIndirectly<string>()("string1"); // works
test1.runTestIndirectly()("5555"); // fails:
// Argument of type '"5555"' is not assignable to parameter of type 'never'.
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.