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

The typing of D.update / D.updateUnsafe #74

Open
ssnielsen opened this issue Mar 3, 2023 · 3 comments
Open

The typing of D.update / D.updateUnsafe #74

ssnielsen opened this issue Mar 3, 2023 · 3 comments
Assignees
Labels
bug Something isn't working

Comments

@ssnielsen
Copy link

ssnielsen commented Mar 3, 2023

I came across a use-case of D.update and D.updateUnsafe that gave me a bit of trouble wrt. its typing.

Example (granted, a bit contrived):

// If I have an object of this shape
const myObject = {
	name: string;
};

// And then use D.update / D.updateUnsafe to change name
const myChangedObject = D.updateUnsafe('name', object => object.name.split(''));

Intuitively, I'd expect the type of myChangedObject.name to be string[], but in practice, it becomes string & string[] (i.e. the original type of name is combined with the return type of the updater function).

Looking at the typings of D.update and D.updateUnsafe, the result of my example definitely makes sense, but I'm wondering a bit why the typings includes the original type of the updated property to begin with 🤔

Happy to hear your takes on this!

@mobily mobily added the bug Something isn't working label Mar 3, 2023
@mobily mobily self-assigned this Mar 3, 2023
@JUSTIVE
Copy link
Sponsor

JUSTIVE commented Jan 22, 2024

could be fixed easily by changing the signature of the update function with

export declare function update<T, K extends keyof T, R>(dict: T, key: K, fn: (value: T[K]) => R): {[Kx in Exclude<keyof T,K>]:T[Kx]} & {[Kx in K]:R} & {};

here's the result in my local environment
image

the output type could be optimized, by removing & with export type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {}; for better readability.

@JUSTIVE
Copy link
Sponsor

JUSTIVE commented Jan 22, 2024

btw, unlike other fp languages, typescript can infer keyof T type in compile-time, so the value of T[K] should be typeof T[K] instead of Option<T[K]>, I guess.

@JUSTIVE
Copy link
Sponsor

JUSTIVE commented Mar 11, 2024

revisited this issue, seems D.update has been fixed in 4.0.0, but updateUnsafe isn't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants