Custom Types

Type Definitions

FlowScript is a structurally typed language, but it is possible to create named types. Using a named type allows you to deserialize JSON, or write groups of functions operating on the same type of data without a lot of repetition.

// Example: define a record type called User, then define
// a function which accepts a User as its argument.
type User = {
    name: text,
    email: text,
    gropIds: number*
};

function getEmail(user: User) => user.email;

let u = new User {
    name: "Florian",
    email: "florian@example.com",
    gropIds: [1, 2]
};

return getEmail(u);

Note that all values in this program are still structurally typed. In other words, the following permutation is perfectly valid:

// assuming the same definitions as above

let u2 = {
    name: "Joe",
    email: "joe@example.com",
    gropIds: [0, 8],
    department: "Accounting" // this member is not in the type.
};
return getEmail(u2);

In other words, the getEmail function accepts all records which have at least the members defined in the User type. There is no requirement that they be created using the new User construct, and they are allowed to have additional members not listed in the type. (For in-depth information, refer to the appendix on subtyping rules.)

Advanced: Generic type definitions

Like functions, types can be generic. Type variables are written in angle brackets after the type name.

type Response<T> = {
    timestamp: datetime,
    data: T
};

function getSomeNumber(): Response<number> {
    return new Response<number> { timestamp: now(), data: random(1, 10) };
}

return getSomeNumber();

Last updated