【问题标题】:TypeScript: How to convert type properties to class membersTypeScript:如何将类型属性转换为类成员
【发布时间】:2021-01-22 22:27:58
【问题描述】:

我得到了这种类型:

type User = {
  name: string;
  email: string;
  password: string;
}

另一方面,我得到了可以扩展并传递一些字段的抽象类。如果我想将 User 属性作为此类中的字段,我需要传递每个单独的字段,如下所示:

abstract class UserModel {
  name: User['name'];
  email: User['email'];
  password: User['password'];
}

这当然很不方便,因为我必须重复我在其他地方的所有信息。

有没有什么方法可以使用某些特定的语法自动执行此操作?

【问题讨论】:

    标签: typescript class types


    【解决方案1】:

    您确定要在这里创建一个抽象类吗?

    解决方案一:没有抽象类

    interface User {
      name: string;
      email: string;
      password: string;
    }
    
    class Bob implements User {
      email = 'bob@bobson.com';
      name = 'Bob';
      password = 'bobson666';
    }
    

    解决方案二:使用抽象类

    您可以使用接口来定义您的属性并实现它旁边的类:

    interface UserModel {
      name: string;
      email: string;
      password: string;
    }
    
    abstract class UserModel {
      name = 'Bob'; // Correct
      name = 42; // Error: Subsequent property declarations must have the same type.  Property 'name' must be of type 'string', but here has type 'number'.(2717)
    }
    

    在同一范围内拥有 classinterface 会使 TypeScript 合并它们的定义,因此您无需重复自己,同时在分配属性时仍保持类型安全。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2023-02-11
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多