26
loading...
This website collects cookies to deliver better user experience
const someObj = { tags: [], packages: [] };
function hasValue(key, item) {
return someObj[key].indexOf(item) !== -1;
}
type SomeType = {
tags: (string | number)[];
packages: string[];
};
const someObj: SomeType = { tags: [], packages: [] };
hasValue
without using some sort of casting. This is your best attempt:function hasValue<K extends keyof SomeType>(key: K, item: SomeType[K]) {
return someObj[key].indexOf(item) !== -1;
// ^^^^
// Argument of type 'SomeType[K]' is not assignable to parameter of type 'string'.
// Type '(string | number)[] | string[]' is not assignable to type 'string'.
// Type '(string | number)[]' is not assignable to type 'string'
//
}
hasValue
. You feel excited, and start to add more types, more code!type Getter<Obj, Param> = (o: Obj) => Param;
function hasValue<Val>(getter: Getter<SomeType,Val[]>, item: Val) {
return getter(someObj).indexOf(item) !== -1;
}
type Setter<Obj, Param> = (o: Obj, val: Param): void;
function resetIfHasValue<Val>(
getter: Getter<SomeType,Val[]>,
setter: Setter<SomeType,Val[]>,
item: Val
) {
if(hasValue(getter,val)){
setter(someObj,[])
}
}
type Modifier<Obj, Param>
= Setter<Obj, Param>
& Getter<Obj, Param>;
type Setter<Obj, Param> = {
set(o: Obj, val: Param): void;
};
type Getter<Obj, Param> = {
get(o: Obj): Param;
};
function resetIfHasValue<Val>(
modifier: Modifier<SomeType,Val[]>,
item: Val
) { ... }
const keyModifier = <Obj>() => <Key extends keyof Obj>(
key: Key
): Modifier<Obj, Obj[Key]> => ({
set(o: Obj, val: Obj[Key]) {
o[key] = val;
},
get(o: Obj): Obj[Key] {
return o[key];
},
});
const tags = keyModifier<SomeType>()("tags")
const packages = keyModifier<SomeType>()("packages")
resetIfHasValue(tags, 1)
resetIfHasValue(tags, "dd")
resetIfHasValue(packages, "asd")