Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 让类从类型别名继承_Javascript_Class_Inheritance_Flowtype - Fatal编程技术网

Javascript 让类从类型别名继承

Javascript 让类从类型别名继承,javascript,class,inheritance,flowtype,Javascript,Class,Inheritance,Flowtype,我尝试创建一个用户类,并希望能够从类型别名继承: type PlainUser = { email: string } class User extends PlainUser { constructor (initialValues: PlainUser) { this.email = initialValues.email } update () { ... } } 这当然不起作用,但我希望有以下语义,而不必复制电子邮件(以及为保持简短而未显示的所有其他字段): f

我尝试创建一个用户类,并希望能够从类型别名继承:

type PlainUser = { email: string }

class User extends PlainUser {
  constructor (initialValues: PlainUser) {
    this.email = initialValues.email
  }

  update () { ... }
}
这当然不起作用,但我希望有以下语义,而不必复制
电子邮件
(以及为保持简短而未显示的所有其他字段):


flow可以实现这一点吗?

据我所知,但您至少可以使用
实现
用户
类实现
普通用户
接口(是的,您必须将其更改为接口)

()

由于
Foo
未指定
email
属性,上述代码导致流v0.41出现以下错误:

7: class Foo implements PlainUser {
                        ^ property `email` of PlainUser. Property not found in
7: class Foo implements PlainUser {
         ^ Foo

当然,这不是你想要的。但至少您会自动检查
User
是否实现了
PlainUser
,而不是什么都没有。

您只能从类进行扩展,并且您的类型别名是一个接口,因此您必须在此处使用
implement
。TypeScript Salsa允许执行以下操作,因为:

如果不使用salsa,则必须显式声明继承的属性:

type PlainUser = { email: string };

class User implements PlainUser {
    public email: string;
    constructor (initialValues: PlainUser) {
        this.email = initialValues.email;
    }
}

我承认一开始这是一个让人头疼的问题,但是像你想做的事情是很有可能的。这确实需要重新思考一下方法

首先,您需要从
类开始,而不是从对象文本开始。直觉上这是有道理的,因为这也是javascript的工作方式

class User {
  email: string;
}
接下来要使用flow的
$Shape
转换。这会将您的类型强制转换为类的可枚举属性

type PlainUser = $Shape<User>;

const Bob: PlainUser = { email: "bob@bob.com" }
最后,像平常一样扩展用户类

class AdminUser extends User {
  admin: true;
}

问题是关于Flowtype的,因此这似乎不能回答问题。
class User {
  email: string;
}
type PlainUser = $Shape<User>;

const Bob: PlainUser = { email: "bob@bob.com" }
const BobProperties: PlainUser = { ...new PlainUserClass("bob@bob.com") }
class AdminUser extends User {
  admin: true;
}