I’m attempting to make a record type that has an int
literal as one of the fields, but can’t quite figure out how to accomplish this. Something like this:
type Entity = {
version: 0, // Error: "Missing a type here"
name: string,
}
type Entity1 = {
version: 1,
name: string,
age: int,
}
You can accomplish this with polymorphic variants:
type entity = {
version: [#0],
name: string,
}
type entity1 = {
version: [#1],
name: string,
age: int,
}
Maybe you can tell us more about what you’re trying to achieve?
4 Likes
Just marking the version of an evolving type, this was a perfect solution, thanks!
In languages like Typescript and Scala 3 you can use any literal value as a type and create unions of literal values as a type
Literal types in typescript, source:
// Literal union type
type Easing = "ease-in" | "ease-out" | "ease-in-out";
const someEasing : Easing = "ease-in"
Scala also supports literal types, source for example you can have a subset of type int
of numbers 1 to 3 as 1 | 2 | 3
// the following constant can only store any integer from 1 to 3
val three: 1 | 2 | 3 = 3
Indeed, that seems to be a killing feature of an “avant-garde” type system in 2022
well you can also do that in Rescript
// Literal union type
type easing = [ | #easeIn | #easeOut | #easeInOut ]
let someEasing : easing = #easeIn
let someEasingString: string = someEasing :> string
or
// the following constant can only store any integer from 1 to 3
let three: [ #1 | #2 | #3] = #3
let threeInt: int = three :> int
2 Likes
thanks @tsnobip, looks like they fit the purpose of typescript literal types with an intentional different syntax
from rescript docs
Poly variants are great for JavaScript interop. For example, you can use it to model JavaScript string and number enums like TypeScript, but without confusing their accidental usage with regular strings and numbers.