Types

Set of types to describe your models.

Types.Object

Types.Object(properties: { [key: string]: Type | Type[] }): Type[]

Example:

Types.Object({
    name: Types.String(),
    address: Types.Object({
        city: Types.String(),
        country: Types.String()
    })
});

Types.Boolean

Types.Boolean(): Type

Example:

Types.Object({
    isAdult: Types.Boolean()
});

Types.Date

Types.Date(): Type

Example:

Types.Object({
    dateCreated: Types.Date()
});

Types.Email

Types.Email(): Type

Example:

Types.Object({
    email: Types.Email()
});

Types.Number

Types.Number(): Type

Example:

Types.Object({
    age: Types.Number()
});

Types.String

Types.String(): Type

Example:

Types.Object({
    name: Types.String()
});

Reference

Type

Types' return value. Although "String" is used in the below examples, the documentation apply to any other methods returning a Type as well.

Type.required

Types.String().required(isRequired: boolean): Type

Mark a property as required or not. Objects missing required properties will be filtered out.

Type.defaultValue

Types.String().defaultValue(defaultValue: any): Type

Provide a default value for a property when it's null. The value provided to this function will go through the type's deserializer.

Type.alias

Types.String().alias(alias: string): Type

By default, you can identify a type's property by reading it with .get('key'). In certain case, you might want to have a different identifier. That's where alias is useful. It's an alternative identifier for a property. Calling .get('alias') will return the key if the property doesn't have an alias.

Type.get

Types.String().get(key: string): any

Read from the type definition, basically to retrieve the values set by the preceding methods.

Adding a custom type

To create your own type, you can extend GenericType as follows:

import { GenericType } from 'react-sheets-import';

class URLType extends GenericType {
    deserialize(value: any): string | any {
        if (typeof value !== 'string') {
            return this.get('defaultValue');
        }
        
        return /https?:\/\//.test(value) ? value : this.get('defaultValue');
    }
}

export default () => new URLType();

The URLType defined above can be used as follows:

import { Types } from 'react-sheets-import';
import URLType from './URLType';

const blog = Types.Object({
    url: URLType().required().defaultValue('https://acme.com')
});

Last updated