Description
Here is a draft of an idea I have had a long time ago. It is not complete. I don't know if this kind of feature could be possible and coherent. I just submit it as is.
The Types Metadata
This is JavaScript data that represents the TypeScript types.
Primitive types
{type: 'string'}
{type: 'number'}
{type: 'boolean'}
Literal types
They are simply represented by their values.
Unions (|
), Intersections (&
)
{
type: '|',
items: [...types here...]
}
{
type: '&',
items: [...types here...]
}
Interfaces
{
type: 'object',
members: {
member1: ...type here...,
member2: ...type here...
}
}
{
type: 'indexer',
index: ...type here...,
indexMember: ...type here...,
members: {
member1: ...type here...,
member2: ...type here...
}
}
{
type: 'function',
name: ...string here...,
arguments: [...types with names here...]
}
Additionaly, each type object can have a name
member, when it is used as a function argument.
There is something to be found to represent optional members. Maybe a suffix '?' in the member name? However, all metadata should remain the same with or without the strictNullCheck
option.
A syntax to import the metadata in the TypeScript code
We need something that can be opened and then closed. Maybe ~~
?
~~ here the metadata code ~~
The metadata code is evaluated at compile time, and replaced by a type data. In the metadata code, each type name is a constant to which the type value is assigned.
For example, here is a TypeScript code that uses metadata:
type Color = 'blue' | 'orange' | 'red'
let colors = ~~Color.items~~
This code is equivalent to:
type Color = 'blue' | 'orange' | 'red'
let colors = ['blue', 'orange', 'red']
NB: Here the inferred type of colors
is string[]
.
Use case
The main use case I see would be, to make robust DRY code to check JSON data.