TypedConverter
Convert object into classes match with TypeScript type annotation
Convert Primitive Type
import createConverter from "typedconverter";
const convert = createConverter()
const numb = convert("12345", Number)
const numb = convert("YES", Boolean)
const numb = convert("2019-1-1", Date)
Specify type on configuration
Expected type can be specified in the configuration, than you can omit expected type on the second parameter of the convert
function. Useful when you want to covert several times without specifying expected type.
import createConverter from "typedconverter";
const convert = createConverter({type: Number})
const numb = convert("12345")
const numb1 = convert("-12345")
const numb2 = convert("12345.123")
Convert custom class
TypedConvert uses tinspector to get type metadata, so it aware about TypeScript type annotation.
import createConverter from "typedconverter";
import reflect from "tinspector"
const convert = createConverter()
reflect.parameterProperties()
class AnimalClass {
constructor(
public id: number,
public name: string,
public deceased: boolean,
public birthday: Date
) { }
}
const data = convert({
id: "200",
name: "Mimi",
deceased: "ON",
birthday: "2018-1-1" },
AnimalClass)
Convert Array
Convert into array by providing array of type in the expected type.
import createConverter from "typedconverter";
const convert = createConverter()
const numb = convert(["1", "2", "-3"], [Number])
Custom Converter
Provided custom converter on the configuration
import createConverter from "typedconverter";
const convert = createConverter({
type: Boolean,
converters: [{ key: Boolean, converter: x => "Custom Boolean" }]
})
const numb = convert("True")