TypeScriptで、ジェネリクスを使用したclassを作成したい

前提

TypeScriptで勉強中です。
classを定義したいのですが、思うように挙動しません。

実現したいこと

ジェネリクスを使用した、型付きのclassを作成したい。

classをnewした時に、入る引数としてはオブジェクト("key, valueはどの型か、またいくつ入るのかは、newを宣言するまで不明確)を想定しています。
例えば,,,

typescript

const obj1 = { a: '01', b: '02' } // key, valueはどの型か、またいくつ入るのかは、newを宣言するまで不明確という想定。 const wrappedObj1 = new ObjectWrapper(obj1)

また、classの中にsetter, getterを定義したいのですが、どのように型を定義すればよいかわからず、詰まってしまいました。

該当のソースコード (発生している問題・エラーメッセージ)

typescript

class ObjectWrapper<T> { constructor(private _obj: T) {} get obj(): T { return { ...this._obj } } 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. let result: boolean = false Object.keys(this._obj).forEach((e) => { if (e === key) { this._obj[key] = val // error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. No index signature with a parameter of type 'string' was found on type 'unknown' result = true return } }) return result } get(key: keyof typeof T): T { // error: 'T' only refers to a type, but is being used as a value here. let result: T = undefined // Type 'undefined' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'undefined'. Object.entries(this._obj).find((val) => { if (val[0] === key) { return (result = val[1]) } }) return result } findKeys(val: T): T { const result: T[] = Object.keys(this._obj).filter((key) => { // Type 'string[]' is not assignable to type 'T[]'. Type 'string' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'. return this._obj[key] === val }) return result // Type 'T[]' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'. }}

試したこと

classの引数が不明確な場合は、ジェネリクスを使用したほうが良いというとこまではたどり着いたのですが、そこから先がわからなくなってしまいました。
よろしくお願いいたします。

補足情報(FW/ツールのバージョンなど)

tsconfig.json

{ "compilerOptions": { "module": "commonjs", "target": "es2020", "outDir": "dist", "sourceMap": true, "strict": true }, "include": ["src"], "exclude": ["node_modules"]}

コメントを投稿

0 コメント