###前提・実現したいこと
Webpackを使ったアプリケーションで、Typescriptで配列にメソッドを生やしたいのですが、エラーが出て困っています。
質問は次の3点です。
- ソート後のthisをthisにアサインできないのですが、どのようにするべきでしょうか?
- Typescriptではどのようにコレクションを実装するべきでしょうか?
- lodashの箇所でキャストせずにUser[]とArray<User>をまとめる方法はないでしょうか?
因みに、やりたいことをGOで書きますと以下のような感じでになります。
go
1type User struct{ 2 id int64 3} 4type Users []User 5func (this *Users) setUser(user User) { 6 this = append(this, user) 7 // ソートする.... 8} 9 10func main() { 11 u := User{} 12 us := &Users{} 13 us.setUser(u); 14}
###発生している問題・エラーメッセージ
エラーメッセージ:
Errro: [ts] Type 'Users' is not assignable to type 'this'.
###該当のソースコード
typescript
1 2import { 3 uniqBy, 4 remove, 5 orderBy, 6 find, 7 remove, 8 findIndex, 9} from 'lodash'; 10 11 12export class User extends Object { 13 id: string; 14 constructor() { 15 super(); 16 } 17} 18 19export class Users extends Array<User> { 20 constructor() { 21 super(); 22 23 // Set the prototype explictilly 24 // see https://github.com/Microsoft/TypeScript/issues/12123#issuecomment-265014802 25 Object.setPrototypeOf(this, Users.prototype); 26 27 } 28 29 /** 30 * 1件追加 31 * @param {User} user 32 */ 33 setUser(user: User): void { 34 let users = this; // 現状のコレクションをコピー 35 users.push(user); 36 // ソート 37 users = remove<User>(users, undefined) as Users; // Errro: [ts] Type 'Users' is not assignable to type 'this'. 38 39 users = uniqBy<User>(users, 'id') as Users; 40 users = orderBy<User>(users, ['created_at'], ['asc']) as Users; 41 this.splice(0, this.length); // コレクションの初期化 42 Object.assign(this, users); // コレクションを更新 43 } 44}
###補足情報(言語/FW/ツール等のバージョンなど)
"typescript": "2.5.2", "webpack": "2.4.1", "lodash": "4.17.4",

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。