typescript - 可以省略 Typescript 类上的泛型类型

标签 typescript class generics

使用带有默认编译器选项的 Typescript 对允许或不允许的内容非常严格——比如空值,类属性不在构造函数中初始化。但是当涉及到泛型时,可以为一个类定义一个泛型类型,然后在不指定类型的情况下创建一个新类!

class Foo<T> {
    bar(item: T): void {
        console.log('typeof T: ', typeof item)
    }
}

const foo1 = new Foo<string>() // T specified
foo1.bar('hello')
foo1.bar(6) // error TS2345: Argument of type '6' is not assignable to parameter of type 'string'

const foo2 = new Foo() // T missing
foo2.bar('hello')
foo2.bar(6) // works with no complaint

是否可以将 new Foo() 视为错误语句?

如上所述,我使用的是默认编译器选项,该选项不允许添加永远不会初始化的额外属性 a: T

最佳答案

你不能在构造函数中遗漏 T 一个错误(当然你可以,但你需要一些条件类型魔法和一个至少有一个参数的构造函数)

如果没有提供任何参数,您可以通过使用类型参数的默认值来使类不可用。默认的 never 就可以了。

class Foo<T = never> {
    bar(item: T): void {
        console.log('typeof T: ', typeof item)
    }
}

const foo1 = new Foo<string>() // T specified
foo1.bar('hello')
foo1.bar(6) // error TS2345: Argument of type '6' is not assignable to parameter of type 'string'

const foo2 = new Foo() // T missing
foo2.bar('hello') // err
foo2.bar(6) // err 

您还可以在剩余参数中使用构造函数重载和元组来创建一个构造函数,如果您省略类型参数(即类型参数是never),该构造函数将给出错误

class Foo<T = never> {
    constructor(...a: T extends never ? ['No T was specified']:[])
    constructor() {

    }
    bar(item: T): void {
        console.log('typeof T: ', typeof item)
    }
}


const foo1 = new Foo<string>() // T specified
foo1.bar('hello')
foo1.bar(6) // error TS2345: Argument of type '6' is not assignable to parameter of type 'string'

const foo2 = new Foo() // T missing, error!
foo2.bar('hello')//err
foo2.bar(6) //err

关于typescript - 可以省略 Typescript 类上的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53570129/

相关文章:

javascript - 如何在 typescript 中编写一个类型,其中一个值的类型将取决于对象中另一个值的类型

javascript - 循环遍历包含 bool 值的对象

java - 通用方法不适用于参数

reactjs - 将泛型类型的实现传递给 React 组件 props

javascript - typescript ,如何引用未导出的 OAuth2Client? google-api-nodejs-客户端

C# "this"过度使用?

php - 在 PHP 的类中包含文件

java - 有没有办法在方法中访问调用类的变量?

c# - 在 MEF 中导出泛型

java - 实例化泛型