typetype: use object spread to create typescript type

TypeType is designed to generate complex typescript type with ease. Usage > npm i -D … Read more typetype: use object spread to create typescript type

TypeType is designed to generate complex typescript type with ease.

url-parser[1] example, function parseURL will be translated to generic type parseURL<text> in typescript:

// input
type function parseURL = (text) => ^{
    if (parseProtocol<text> extends [infer protocol, infer rest]) {
        return {
            protocol,
            rest
        }
    } else {
        return never
    }
}
// output
type parseURL<text> = parseProtocol<text> extends [infer protocol, infer rest]
  ? {
      protocol: protocol;
      rest: rest;
    }
  : never;

Conditional type is presented in this way:

^{ if ... else ...}

It can be nested so that the logic is clear:

type function _isNumberString = (text) => ^{
    if(text extends "") {
        return true
    } else if(text extends `${infer digit}${infer rest}`) {
        return ^{
            if(digit extends Digit) {
                return _isNumberString<rest>
            } else {
                return false
            }
        }
    } else {
        return false
    }
}

an intersection type combines multiple types into one[2], we use combine [...] or & [...] for intersection type:

type i1 = combine [{ a: 1 }, { b: 2 }]
type i2 = & [{ a: 1 }, { b: 2 }]

ts-toolbelt[3], for example: polyfill/global.d.ts[4].

react-peg[5] to write parser, as you can see in ./src/parser/expression[6], generator is even simpler than parser, in ./src/generator/generator[7], typetype AST is used to generate corresponding babel AST.

MIT licensed[8].

References

  1. ^ url-parser (github.com)
  2. ^ an intersection type combines multiple types into one (www.typescriptlang.org)
  3. ^ ts-toolbelt (github.com)
  4. ^ polyfill/global.d.ts (github.com)
  5. ^ react-peg (github.com)
  6. ^ ./src/parser/expression (github.com)
  7. ^ ./src/generator/generator (github.com)
  8. ^ MIT licensed (github.com)


Source: Echo Js


Categories: Development, Software


Leave a Reply

Your email address will not be published. Required fields are marked *