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
k
as the key toc
. Since you mention you expectk
to be akeyof ILPAsset
that would meanc
should beILPAsset
. So the signature should be:The left over problem is that now the index access
c[k]
will not be of typestring
sinceILPAsset
contains bothnumber
andstring
keys.We have two solutions for this.
We could check if
c[k]
is astring
and if it not returnnull
:We could also filter the keys so
k
can only be a key taht would be astring
Note: The only
string
key ofILPAsset
issymbol
so perhaps you should evaluate the need for thek
parameter at all. Why not just accessc.symbol
?