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

Feature request: Override and extend callback argument #58788

Open
6 tasks done
finom opened this issue Jun 6, 2024 · 0 comments
Open
6 tasks done

Feature request: Override and extend callback argument #58788

finom opened this issue Jun 6, 2024 · 0 comments
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@finom
Copy link

finom commented Jun 6, 2024

πŸ” Search Terms

extend callback argument typescript

βœ… Viability Checklist

⭐ Suggestion

(Possibly a duplicate, but I couldn't find similar issue)
I often need to change type of a callback argument and it always takes an extra line to perform as assertions. I propose to add ability to use as keyword directly on the argument.

function withCallback(callback: (arg: { foo: string }) => void) {
  // ...
}

withCallback((arg) => {
  const { foo, bar } = arg as { foo: string; bar: string }; // always an extra line
  // ...
});

πŸ“ƒ Motivating Example

It would be nice to have a built-in TS feature that makes possible to do that in a shorter manner:

withCallback(({ foo, bar } as { foo: string; bar: string }) => {
  console.log(foo, bar);
});

// or
withCallback(({ foo, bar } as unknown as { foo: string; bar: string }) => {
  console.log(foo, bar);
});

Overriding the type completely isn't needed too often that's why I propose to also enrich this syntax with extends (or something more applicable) keyword:

withCallback(({ foo, bar } as extends { bar: string }) => {
  console.log(foo, bar);
});

Thinking thru it I think it would make sense to also add as extends for other often appearing use-cases:

const x = { foo: 'foo' };

const y = x as extends { bar: string };
// same as 
const y = x as typeof x & { bar: string };

as extends T at this syntax can be interpreted as as typeof __SELF__ & T

πŸ’» Use Cases

There are million use-cases for this feature. Type assertions in TS are used more often than we might expect while learning it.

@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature labels Jun 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants