繁体   English   中英

如何在没有类型定义的情况下定义泛型类型“具有属性”约束?

[英]How to define generic type 'has property' constrint without type definition?

假设我们必须实现以下内容:

export class Class1<T> {
    public constructor(param1: T) {
        param1.prop1 = 1; // TS error: T doesn't have property 'prop1'
    } 
}

鉴于我们无法从单个基interface `class` 继承所有可能的param1 ,如何约束T

我试过T extends { prop1: number } ,但它的 TS 语法不正确。

我在问题中给出的解决方案是正确的:

export class Class1<T extends { prop1: number }> {
    public constructor(param1: T) {
        param1.prop1 = 1; // No TS error now
    } 
}

看来我对 VS Code 的内置错误检查器有一些问题。

暂无
暂无

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

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