前提
TypeScriptで勉強中です。
classを定義したいのですが、思うように挙動しません。
実現したいこと
ジェネリックを使用した、型付きのclassを作成したい。
classをnewした時に、入る引数としてはオブジェクト("key, valueはどの型か、またいくつ入るのかは、newを宣言するまで不明確)を想定しています。
例えば,,,
typescript
1const obj1 = { a: '01', b: '02' } // key, valueはどの型か、またいくつ入るのかは、newを宣言するまで不明確という想定。 2const wrappedObj1 = new ObjectWrapper(obj1)
また、classの中にsetter, getterを定義したいのですが、どのように型を定義すればよいかわからず、詰まってしまいました。
該当のソースコード (発生している問題・エラーメッセージ)
typescript
1class ObjectWrapper<T> { 2 /*** 3 * 引数のオブジェクトのコピーを this._objに設定 4 */ 5 constructor(private _obj: T) {} 6 7 /** 8 * this._objのコピーを返却 9 * @return Object 10 */ 11 get obj(): T { 12 return { ...this._obj } 13 } 14 15 /** 16 * this._obj[key] に valを設定。keyがthis._objに存在しない場合、falseを返却 17 * @param key オブジェクトのキー 18 * @param val オブジェクトの値 19 */ 20 set(key: keyof typeof T, val: keyof typeof T): boolean { // error: 'T' only refers to a type, but is being used as a value here. 21 let result: boolean = false 22 23 Object.keys(this._obj).forEach((e) => { 24 if (e === key) { 25 this._obj[key] = val // error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. 26 No index signature with a parameter of type 'string' was found on type 'unknown' 27 result = true 28 return 29 } 30 }) 31 32 return result 33 } 34 35 /** 36 * 指定したキーの値のコピーを返却 37 * 指定のキーが存在しない場合 undefinedを返却 38 * @param key オブジェクトのキー 39 */ 40 get(key: keyof typeof T): T { // error: 'T' only refers to a type, but is being used as a value here. 41 let result: T = undefined // Type 'undefined' is not assignable to type 'T'. 42 'T' could be instantiated with an arbitrary type which could be unrelated to 'undefined'. 43 44 Object.entries(this._obj).find((val) => { 45 if (val[0] === key) { 46 return (result = val[1]) 47 } 48 }) 49 50 return result 51 } 52 53 /** 54 * 指定した値を持つkeyの配列を返却。該当のものがなければ空の配列を返却。 55 */ 56 findKeys(val: T): T { 57 const result: T[] = Object.keys(this._obj).filter((key) => { // Type 'string[]' is not assignable to type 'T[]'. 58 Type 'string' is not assignable to type 'T'. 59 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'. 60 return this._obj[key] === val 61 }) 62 63 return result // Type 'T[]' is not assignable to type 'T'. 64 'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'. 65 } 66}
試したこと
classの引数が不明確な場合は、ジェネリックを使用したほうが良いというとこまではたどり着いたのですが、そこから先がわからなくなってしまいました。
よろしくお願いいたします。
補足情報(FW/ツールのバージョンなど)
tsconfig.json
1{ 2 "compilerOptions": { 3 "module": "commonjs", 4 "target": "es2020", 5 "outDir": "dist", 6 "sourceMap": true, 7 "strict": true 8 }, 9 "include": ["src"], 10 "exclude": ["node_modules"] 11}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/06/13 23:10