Typescript: Conditional Types, implement custom error message for non matching case

Created on 27 Aug 2019  路  2Comments  路  Source: microsoft/TypeScript

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:

  • [X] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [X] This wouldn't change the runtime behavior of existing JavaScript code
  • [X] This could be implemented without emitting different JS based on the types of the expressions
  • [X] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [X] This feature would agree with the rest of TypeScript's Design Goals.

Most helpful comment

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.

All 2 comments

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.

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

uber5001 picture uber5001  路  3Comments

weswigham picture weswigham  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

siddjain picture siddjain  路  3Comments

dlaberge picture dlaberge  路  3Comments