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

SyncFunction type #35

Open
alcuadrado opened this issue Apr 25, 2019 · 5 comments
Open

SyncFunction type #35

alcuadrado opened this issue Apr 25, 2019 · 5 comments
Labels
enhancement New feature or request ts issue

Comments

@alcuadrado
Copy link

Hi Crhis!

I'm wondering if it's possible to define a type that forbids async functions. I'll explain why I'd like something like that, and what I tried so far.

Suppose I have a function like this one:

function receivesACallback(c:() => any) {
  c();
  doSomethingElse();
}

Passing an async function to receivesACallback can be problematic, as it doesn't await it.

My best try so far is this:

type SyncFunction<T> = () => Exclude<T, Promise<any>>;

function notAsyncCallback<T>(callback: SyncFunction<T>) {
  callback();
  doSomethingElse();
}

notAsyncCallback(() => {});
notAsyncCallback(() => 123);

notAsyncCallback(async () => {}); // Type error
notAsyncCallback(async () => 123); // Type error

I don't like having to define a useless type param though.

Do you find this idea interesting? And do you know how to do it without the type param?

@krzkaczor
Copy link
Collaborator

Oh, that's pretty useful, floating promises are cancer. I think SyncFunction type would be a pretty cool addition to ts-essentials 👍

I don't see a way to do this without type parameter right now. Probably Negated types that are cooking in TS backlog as we speak would solve this: microsoft/TypeScript#29317

@alcuadrado
Copy link
Author

I don't think this can be achieved without the type parameter either.

The not proposal is very interesting! It even has an example related to this:

declare function ignore<T extends not (object & Promise<any>)>(value: T): void;
declare function readFileAsync(): Promise<string>;
declare function readFileSync(): string;
ignore(readFileSync());     // OK
ignore(readFileAsync());    // Should error

@krzkaczor
Copy link
Collaborator

@all-contributors please add @alcuadrado for ideas

@allcontributors
Copy link
Contributor

@krzkaczor

I've put up a pull request to add @alcuadrado! 🎉

@Beraliv Beraliv added the enhancement New feature or request label Aug 15, 2021
@Beraliv
Copy link
Collaborator

Beraliv commented Mar 5, 2023

Is it possible to do with ESLint rule? https://typescript-eslint.io/rules/no-floating-promises/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request ts issue
Projects
None yet
Development

No branches or pull requests

3 participants