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

gab*_*iel 1 generics class typescript

使用具有默认编译器选项的 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
Run Code Online (Sandbox Code Playgroud)

这是否可以被new Foo()视为错误的陈述?

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

Tit*_*mir 5

您不能使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 
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)