简体   繁体   English

在TypeScript泛型中,类型声明不是必需的

[英]Type declaration is not mandatory in TypeScript generics

Short example of the issue I want to ask about in TypeScript: 我想在TypeScript中询问的问题的简短示例:

export class Test {
    public runTest<T>(param: T): T {
        return param;
    }
}

let test1: Test = new Test();
test1.runTest<string>("string1");
test1.runTest("5555");

Both "runTest" statements will execute normally. 这两个“ runTest”语句都将正常执行。 First will require you to pass a string (which is great), second - not really. 首先要求您传递一个字符串(很棒),其次-并非如此。 But I want to make it mandatory for anyone using "runTest" to pass some type into T. 但我想强制所有使用“ runTest”的人将某种类型传递给T。

Can it be done? 能做到吗 Can't figure out a way to do it via code. 无法找到通过代码完成此操作的方法。 Also tried looking for TSLint rule that could help, but also found none. 还尝试寻找可能有帮助的TSLint规则,但未找到任何规则。

Thanks 谢谢

If you really want to get this done (I'm not going to worry about why you're doing this), you need to convince TypeScript to infer some bad type for T when you leave it out, so that it will fail to run the test. 如果您真的想完成此操作(我不必担心为什么要这样做),则需要说服TypeScript在不使用T情况下推断出一些错误的类型,以免它无法运行考试。 I can't figure out how to do it directly, but here's an indirect way: 我不知道如何直接执行此操作,但这是一种间接方法:

export class Test {
    public runTestIndirectly<T = never>(): (t:T)=>T {
      return (t:T)=>t  
    }
}

So runTestIndirectly() produces a function which behaves like runTest . 因此, runTestIndirectly() 会产生一个功能类似于runTest的函数。 The type of T is inferred when you call runTestIndirectly() , which has no access to the type of object you pass to the function it produces. 当您调用runTestIndirectly() ,将推断出T的类型,该类型无权访问传递给它产生的函数的对象的类型。 And if you have T default to never , you will get a failure when you neglect to specify T to something that works: 而且,如果您将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'.

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM