Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ts-lens): Have the fallback dictate type #2

Merged
merged 1 commit into from
Dec 19, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/lens.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
const getKey = <T, Key extends keyof T>(key: Key) => (value: T): T[Key] =>
value && value[key];

const getOrKey = <T, Key extends keyof T, OrValue>(
const getOrKey = <T, Key extends keyof T, OrValue extends T[Key]>(
key: Key,
orValue: OrValue & T[Key]
) => (value: T): T[Key] => (value && value[key]) || orValue;
orValue: OrValue
) => (value: T): OrValue => {
if (value && value.hasOwnProperty(key)) {
return (value && value[key]) as any;
}
return orValue;
};

const setKey = <T, Key extends keyof T>(key: Key, setValue: T[Key]) => (
value: T
Expand Down Expand Up @@ -62,10 +67,13 @@ export class Lens<A extends {}, B> {
/** Like thenKey but now we have a default
* Ex: Get a value in a model dictionary or return the default
*/
public thenKeyOr<Key extends keyof B, C>(key: Key, defaultValue: C & B[Key]) {
public thenKeyOr<Key extends keyof B, C extends B[Key]>(
key: Key,
defaultValue: C
) {
return this.then(
new Lens(getOrKey(key, defaultValue), (value: C & B[Key]) =>
setKey<B, Key>(key, value)
new Lens<B, C>(getOrKey(key, defaultValue), (value: C) =>
setKey<B, Key>(key, value as any)
)
);
}
Expand Down