I study generics. In the code:

class Dictionary<TKey, TValue> { private _data: KeyValuePair<TKey, TValue>[] = []; add(key: TKey, value: TValue): void { const entry = new KeyValuePair<TKey, TValue>(); entry.key = key; entry.value = value; this._data.push(entry); } get(key: TKey): TValue | null { return this._data.find(el => el.key === key); // <-- } } 

tsconfig.json:

 { "compilerOptions": { "module": "commonjs", "target": "es5", "sourceMap": true, "lib": ["esnext", "es5", "es6", "es7", "es2015", "es2016", "es2017", "es2018"] }, ... } 

Error: (70, 23) TS2339: Property 'find' does not exist on type 'KeyValuePair []'.

Why is this error, because I declared that the array?

  • What do you have in the lib property in tsconfig 'e? - overthesanity
  • I have no such property in tsconfig. - Denni Adam pm
  • why? - overthesanity pm

1 answer 1

In your example, the type KeyValuePair not defined.
And the result type of the get method is inconsistent.

 class KeyValuePair<Tkey, Tvalue> { key: Tkey; value: Tvalue; } class Dictionary<TKey, TValue> { private _data: KeyValuePair<TKey, TValue>[] = []; add(key: TKey, value: TValue): void { const entry = new KeyValuePair<TKey, TValue>(); entry.key = key; entry.value = value; this._data.push(entry); } get(key: TKey): TValue | null { const result = this._data.find(el => el.key === key); if (result) { return result.value; } else { return null; } } } let dict = new Dictionary<string, number>(); dict.add('a', 1); console.log(dict.get('a'));