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

argument dynamically optional #182

Closed
WORMSS opened this issue Feb 25, 2021 · 3 comments
Closed

argument dynamically optional #182

WORMSS opened this issue Feb 25, 2021 · 3 comments

Comments

@WORMSS
Copy link

WORMSS commented Feb 25, 2021

interface PropMap {
    a: {
        b: string | number;
    };
    c: never | undefined;
}

function func<K extends keyof PropMap, P extends PropMap[K]>(k: K, p: P) {}
function func2<K extends keyof PropMap, P extends PropMap[K]>(k: K, p?: P) {}

/* ✅ */ func('a');            // should error, needs prop.
/* ✅ */ func('a', { b: '' }); // should be fine
/* ✅ */ func('a', { c: '' }); // should error, wrong prop.
/* ❌ */ func('c');            // should be fine, I don't want to pass in props for never|undefined.
/* ✅ */ func('c', undefined); // should be fine
/* ✅ */ func('c', { c: '' }); // should error, should be given no prop 


/* ❌ */ func2('a');            // should error, needs prop.
/* ✅ */ func2('a', { b: '' }); // should be fine
/* ✅ */ func2('a', { c: '' }); // should error, wrong prop.
/* ✅ */ func2('c');            // should be fine, I don't want to pass in props for never|undefined.
/* ✅ */ func2('c', undefined); // should be fine
/* ✅ */ func2('c', { c: '' }); // should error, should be given no prop 

Playground

I hope the above makes sense, but I can't seem to make this act nicely. There is a use case where it breaks.
(I would love to split it into 2 functions, but sadly, it's not my call.)

With func the func('c') breaks because it is saying I NEED to supply a property
so I thought, simple fix.. make p optional.
but as you can see from func2 this makes func('a') not throw an error, when I WANT it to, because it has a P that is not never.

other things I tried was

interface PropMap {
    a: {
        b: string | number;
    };
    c: never;
}

which means I can't pass 'undefined' as the 2nd parameter, which is perfectly fine, I can live with that..

@sindresorhus
Copy link
Owner

How is this related to type-fest?

@WORMSS
Copy link
Author

WORMSS commented Feb 26, 2021

Is it not a type?

@sindresorhus
Copy link
Owner

I don't understand your question.

@WORMSS WORMSS closed this as completed Mar 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants