LoginSignup
kanfutrooper
@kanfutrooper (masaomi)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

TypeScriptのエラーを解消したい

Q&AClosed

TypeScriptのclass文法を勉強しています。
下記箇所にエラーの表示が出ます。
調べてもよくわからずエラーが改善しません。
何方か改善方法を教えてください。

// エラー文①
This condition will always return 'false' since the types '{ [x: string]: string; }' and 'string' have no overlap.

// エラーの波線箇所
(wrappedObj1.get('b') === '04'
interface obj1 { [key: string]: string }

class ObjectWrapper {
  private _obj :obj1

constructor(_obj: obj1) {
     this._obj = { ..._obj };
  }

 get obj() {
    return { ...this._obj };
  }

set(key:string, val: string): boolean {
    if (this._obj[key] !== undefined) {
      this._obj[key] = val;
      return true;
    }
    return false;
  }

get(key:string) {
    return { ...this._obj };
  }
  findKeys(val: unknown):string {
       return keys;
  }
}
const obj1 = { a: '01', b: '02' };
const wrappedObj1 = new ObjectWrapper(obj1);

if (wrappedObj1.obj.a === '01') {
  console.log('OK: get obj()');
} else {
  console.error('NG: get obj()');
}

if (
  wrappedObj1.set('c', '03') === false &&
  wrappedObj1.set('b', '04') === true &&
  wrappedObj1.obj.b === '04'
) {
  console.log('OK: set(key, val)');
} else {
  console.error('NG: set(key, val)');
}

// エラー文①の波線が出る箇所
if (wrappedObj1.get('b') === '04' && wrappedObj1.get('c') === undefined) {
  console.log('OK: get(key)');
} else {
  console.error('NG: get(key)');
}

const obj2 = { a: '01', b: '02', bb: '02', bbb: '02' };
const wrappedObj2 = new ObjectWrapper(obj2);
const keys = wrappedObj2.findKeys('02');
if (
  wrappedObj2.findKeys('03').length === 0 &&
  keys.includes('b') &&
  keys.includes('bb') &&
  keys.includes('bbb') &&
  keys.length === 3
) {
  console.log('OK: findKeys(val)');
} else {
  console.error('NG: findKeys(val)');
}
0

1Answer

get(key:string) {
-   return { ...this._obj };
+   return this._obj[key];
}

じゃないですか?

1

Comments

  1. @kanfutrooper

    Questioner
    @_y_sさん、エラーが解消しました!
    アドバイス、本当にありがとうございました!

Your answer might help someone💌