Skip to content

Add generic properties accessor for complex runtypes #217

Open
@yuhr

Description

@yuhr

I've come up with this idea during investigating #216. Currently, accessing inner runtypes of complex ones such as Record, Tuple, etc. in a generic way requires you to write cumbersome code like following:

runtype.reflect.tag === 'record' ? runtype.reflect.fields : runtype.reflect.tag === 'tuple' ? runtype.reflect.components : ...

But I want to write just this instead:

runtype.properties

This should be possible because JS and TS maintain interoperability between objects and arrays, i.e. arrays can be treated as objects with keys being string of decimal numbers.

If implemented properly, this should also work with Union and Intersect, because TS already does some equivalent stuff for static typing, for example:

type U = { foo: true } | { foo: false };
let u!: U;
u.foo; // inferred as `boolean`

type I = { foo: boolean } & { foo: boolean; bar: string };
let i!: I;
i.foo; // inferred as `boolean`
i.bar; // inferred as `string`

So you should be able to do that on runtypes:

const U = Union(Record({ foo: Literal(true) }), Record({ foo: Literal(false) }));
u.properties.foo; // should be `Union(Literal(true), Literal(false))` or just `Boolean`

const I = Intersect(Record({ foo: Boolean }), Record({ foo: Boolean, bar: String }));
i.properties.foo; // should be `Intersect(Boolean, Boolean)` or just `Boolean`
i.properties.bar; // should be `String`

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions