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

Conditional Types, implement custom error message for non matching case #33098

Closed
5 tasks done
abdulkareemnalband opened this issue Aug 27, 2019 · 2 comments
Closed
5 tasks done

Comments

@abdulkareemnalband
Copy link

abdulkareemnalband commented Aug 27, 2019

Search Terms

#conditionalType , #customErrorMessage

Suggestion

In conditional types never is used to remove invalid types from assignments, Error message is is reported as So and so type cannot be assigned to never , Which does not inform user what are the actual requirements for usecase.

Author of conditional type need to provide some custom error message for particular failure.
this could be provided as doc comment before never
Ex:

type Test<C> = C extends some? C :/** Should extend something*/ never;

Use Cases

Too improve the diagnostics of conditional types.

Examples

type NonData<D> = D extends {data:any}?/**parameter should not contain property data */ never:D;

declare function nonData<T>(param:NonData<T>):void;


const withData = {data:10 , a:'a'};
nonData(withData); // error, but error message is "parameter should not contain property data "

const withNonData = { a:'a'};
nonData(withNonData); // pass

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.
@abdulkareemnalband abdulkareemnalband changed the title Conditional Types, implemnt custom error message for non matching case Conditional Types, implement custom error message for non matching case Aug 27, 2019
@jack-williams
Copy link
Collaborator

jack-williams commented Aug 27, 2019

Duplicate of #23689.

For now I tend to use something like:

type NonData<D> = D extends {data:any} ? [D, 'should not extend { data: any }', never] : D;

which is not fool-proof, but works well enough.

And FWIW, searching "custom error message" will provide #30289 in the first page of results---which is almost exactly what you are asking for.

@abdulkareemnalband
Copy link
Author

@jack-williams thanks
I could not find previous issues,
closing this now in favor of #23689

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