My Code
import * as R from 'ramda';
import { ILPAsset } from 'shared/types/models';
interface TextMatchFunction {
(part: string, typed: string): boolean;
}
const textMatch: TextMatchFunction = (part: string, typed: string) => typed.search(part) !== -1;
export const filterAssets = (txt: string, assets: ILPAsset[]): ILPAsset[] => {
const checkText = (k: string, c: keyof ILPAsset) => (textMatch(txt, c[k].toLowerCase()) ? c : null);
const curriedCheckText = R.curry(checkText);
// @ts-ignore
const bySymbol = R.map(curriedCheckText('symbol'), assets);
return R.reject(R.isNil, bySymbol);
};
IPAsset's interface
export interface ILPAsset {
symbol: string;
lastPayout: number;
historical: number;
}
Problem is on this line:
const checkText = (k: string, c: keyof ILPAsset) => (textMatch(txt, c[k].toLowerCase()) ? c : null);
Typescript expects k to be a number c[k], when it's in fact a key for an object in ILPAsset, which is string that in my case will be symbol.
How would this be handled in Typescript?
UPDATE
A much simpler approach to do this btw, however I got a great answer for future issues in regards to key checking :D
export const filterAssets = (typed: string, assets: ILPAsset[]): ILPAsset[] => {
const checkSymbol = (asset: ILPAsset) =>
asset.symbol.includes(typed.toUpperCase());
return R.filter(checkSymbol, assets);
};
The problem is caused because you are using
kas the key toc. Since you mention you expectkto be akeyof ILPAssetthat would meancshould beILPAsset. So the signature should be:The left over problem is that now the index access
c[k]will not be of typestringsinceILPAssetcontains bothnumberandstringkeys.We have two solutions for this.
We could check if
c[k]is astringand if it not returnnull:We could also filter the keys so
kcan only be a key taht would be astringNote: The only
stringkey ofILPAssetissymbolso perhaps you should evaluate the need for thekparameter at all. Why not just accessc.symbol?