简体   繁体   English

带有 Class 的 Typescript 泛型不起作用或我做错了什么?

[英]Typescript generics with Class does not work or what i am doing wrong?


class Some<AttributeType = {
    bar: string
}> {
    foo(attrs: AttributeType) {
        if (attrs.bar) {
            console.log(attrs.bar)
        }
    }
}

ts failed with error ts 因错误而失败

Property 'bar' does not exist on type 'AttributeType'.

https://www.typescriptlang.org/play?#code/FAYwNghgzlAEDKB7AtgUwDwEEAu2BOAlgEYCu2qAKgJ4AOqsAvLAN7CzuxER4BcsU+AgDsA5sAC+APhZsOAM0SIAFBFx4ofHINLlqdAJQyOx2ATmwVaqADoueQ6xNPYIREKiIwqa2EQjL+DZ2+rJO4qGw4eFAA https://www.typescriptlang.org/play?#code/FAYwNghgzlAEDKB7AtgUwDwEEAu2BOAlgEYCu2qAKgJ4AOqsAvLAN7CzuxER4BcsU+AgDsA5sAC+APhZsOAM0SIAFBFx4ofHINLlqdAJQyOx2ATmwVaqADoueQ6xNPYIREKiIwqa2EQjL+AZ2+r

Use extends keyword instead of = :使用extends关键字而不是=

class Some<AttributeType extends {  bar: string  }>

More here ( TypeScript generic constraints ).更多信息( TypeScript 通用约束)。

By using the = syntax you provided a default generic parameter and you can use your class in a following way:通过使用=语法,您提供了一个默认的通用参数,您可以通过以下方式使用您的类:

let x: Some;

Which would be impossible if you removed it.如果您将其删除,那将是不可能的。 What you need is to define a constraint which will allow the compiler to infer that your generic type always contains bar field.您需要定义一个约束,允许编译器推断您的泛型类型始终包含bar字段。

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

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