Typescript: Suggestion:Validation on defined types

Created on 18 May 2016  路  7Comments  路  Source: microsoft/TypeScript

It would be nice if we could write some kind of validation on user defined types. Something like:

type Integer(n:number) => String(n).macth(/^[0-9]+$/)
let x:Integer = 3 //OK
let y:Integer = 3.6 //wrong

type ColorLevel(n:number) => n>0 && n<= 255
type RGB = {red:ColorLevel, green:ColorLevel, blue:ColorLevel};
let redColor:RGB = {red:255, green:0, blue:0}   //OK
let wrongColor:RGB = {red:255, green:900, blue:0} //wrong

type Hex(n:string) => n.match(/^([0-9]|[A-F])+$/)
let hexValue:Hex = "F6A5" //OK
let wrongHexValue:Hex = "F6AZ5" //wrong

The value that the type can accept would be determined by the function parameter type and by the function evaluation itself. That would solve other issues like #6902, #6579 or #7982

Duplicate

Most helpful comment

These are called Dependent Types: https://en.wikipedia.org/wiki/Dependent_type

A very powerful feature indeed, especially if done generically as opposed to case-by-case (regex, range types, etc). If pursued in this form, we would need to be wary of what is or is not allowed in such type predicates (e.g. no type system within the type predicate), since this could lead to undecidable type checking...

All 7 comments

Looks like the same thing as #6579. i would add implementation suggestions in that issue instead of creating a new one.

Sorry, I thought that should be in a different issue because the other was just about allow regex patterns in types and I'm asking for a more general feature, but I will suggest there.

Thank you!

@mhegazy Is this a duplicate of #6579? The first and third examples could be covered by #6579 but the middle example is not regex based. Furthermore, for the first example, the integer check could (and probably should) be implemented without a regex:

type Integer (n: number) => Math.floor(n) == n;
let x:Integer = 3 //OK
let y:Integer = 3.6 //wrong

@mhegazy If I understand you correctly, the OP provides three examples: Integer, duplicated in #4639; ColorLevel which could be covered by a combination of #15480 and #4639; and Hex which is covered by #6579.

Are there no other possible type validations possible with this?

type Even (n: number) => n % 2 == 0;
type Past (dte: Date) => dte < Date.now();

@mhegazy Considering that the OP's comment on #6579 has (as of this writing) garnered 67 +1s, and this proposal is broader than any of the other more limited special case proposals, can this be reopened?

These are called Dependent Types: https://en.wikipedia.org/wiki/Dependent_type

A very powerful feature indeed, especially if done generically as opposed to case-by-case (regex, range types, etc). If pursued in this form, we would need to be wary of what is or is not allowed in such type predicates (e.g. no type system within the type predicate), since this could lead to undecidable type checking...

Was this page helpful?
0 / 5 - 0 ratings