2017-06-01 34 views
0

我有一個與服務器交談的功能。其中一個獲取參數被稱爲「userstate」。這個userstate是一個對象。我從這個對象得到這個:我該如何在打字稿中將一個無法識別的對象製作成一個類?

userstate = { 
    'username' = '', 
    'display-name' = '' 
}; 

我該如何製作這個類?我此刻這樣的:

extends class Userstate { 
    username: string; 
    displayName: string; 

    constructior() { 
     this.username = this['username']; 
     this.displayName = this['display-name']; 
    } 
} 

而在我的功能我這樣做:

let get_user_stuff = (userstate: Userstate) => { 
    console.log(userstate.username); 
    console.log(userstate.displayName); 
}; 

而且我的控制檯這樣說:

darky_chan 
undefined 

我希望你能幫助我:) 在此先感謝

+0

不伸出我想寫出口 –

+0

可能重複[如何用JSON對象初始化打字稿對象](https://stackoverflow.com/questions/22885995/how-do-i-initialize-a-typescript-object-with- A-JS on-object) – Amid

+0

sry我沒有做過duplucate –

回答

1

你是在找這樣的:

class Userstate { 
    username: string; 
    displayName: string; 

    constructor(jsonObject: any) { // Notice the json object passed to constructor 
     this.username = jsonObject.username; 
     this.displayName = jsonObject['display-name']; 
    } 
} 

let convertToInstance = (jsonObj: any) => (new Userstate(jsonObj)); 

let instance = convertToInstance({ 
    'username': 'name', 
    'display-name': 'd-name' 
}); 

console.log(instance); 
console.log(instance.displayName); 
+0

問題是這樣的:我得到一個對象與 - 。我無法將這個課程作爲一個對象。我想用這個,當我寫它應該告訴我它有什麼功能。 –

+0

例如:用戶。現在我得到一個清單它有什麼。我不想一直這樣做:userstate ['display-name'],因爲我認爲這看起來很糟 –

+0

@Darky_Chan但是,如果沒有'[member-name]'符號,就不能使用'-'來訪問成員。所以你不能'userstate.display-name',如果這是你想要的。我知道你的JSON數據有連字符,但是如果你把它轉換成像我顯示的'Userstate'實例,你可以使用:'instance.displayName' – Saravana

0

根據打字稿specs你可以有一個包含屬性名無效標識符:

class Userstate 
{ 
    username: string; 
    "display-name": string; 
} 

唯一的問題是,你將不得不使用索引來訪問它們:

const u = new Userstate(); 
u["display-name"] = 23; 
相關問題