2017-03-15 120 views
0

我嘗試創建一個用戶類,並且希望能夠從一個類型別名繼承繼承:讓班從類型別名

type PlainUser = { email: string } 

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

    update() { ... } 
} 

這並不當然的工作,但我想有以下無需複製email(和所有其他領域,我不展現給保持簡潔)的語義:

type PlainUser = { email: string } 

class User { 
    email: string 

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

    update() { ... } 
} 

這是可能的流量?

回答

0

不是我所知道的,但是您至少可以使用implements來強制User類實現接口(是的,您必須將其更改爲接口)。

interface PlainUser { 
    email: string; 
} 

class Foo implements PlainUser { 
} 

tryflow

上述代碼產生具有流動v0.41以下錯誤,因爲Foo不指定email屬性:

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

當然,這是不正是你要求的。但至少你正在自動檢查User執行PlainUser,而不是什麼都沒有。

0

你只能從類擴展,而你的類型別名是一個接口,所以你必須在這裏使用implement。打字稿莎莎允許執行以下操作,因爲this suggestion was implemented

type PlainUser = { email: string }; 

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

如果你不使用莎莎,你必須明確地聲明繼承屬性:

type PlainUser = { email: string }; 

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

Playground

+1

的問題是關於流動型,因此這似乎並沒有回答這個問題。 – loganfsmyth

+0

@loganfsmyth哇對,沒有注意到sry。 –

0

我得承認,這是最初是一名頭部抓手,但是像你想做的事情是非常可能的。它確實需要重新考慮這個方法。

首先,您需要以class而不是對象字面值開頭。直覺上這是有道理的,因爲這也是javascript的工作方式。

class User { 
    email: string; 
} 

接下來要使用流程的$Shape轉換。這會將您的類型轉換爲類的可枚舉屬性。

type PlainUser = $Shape<User>; 

const Bob: PlainUser = { email: "[email protected]" } 

const BobProperties: PlainUser = { ...new PlainUserClass("[email protected]") } 

最後,擴展用戶類爲正常。

class AdminUser extends User { 
    admin: true; 
} 

example