•  


GitHub - jadengis/ts-auto-guard: Generate type guard functions from TypeScript interfaces
Skip to content

Generate type guard functions from TypeScript interfaces

Notifications You must be signed in to change notification settings

jadengis/ts-auto-guard

 
 

Repository files navigation

ts-auto-guard

Greenkeeper badge

Generate type guard functions from TypeScript interfaces

A tool for automatically generating TypeScript type guards for interfaces in your code base.

This tool aims to allow developers to verify data from untyped sources to ensure it conforms to TypeScript types. For example when initializing a data store or receiving structured data in an AJAX response.

Install

Yarn

$ yarn add -D ts-auto-guard

npm

$ npm install --save-dev ts-auto-guard

Usage

Annotate interfaces in your project. ts-auto-guard will generate guards only for interfaces with a @see {name} ts-auto-guard:type-guard JSDoc tag.

// my-project/Person.ts


/** @see {isPerson} ts-auto-guard:type-guard */

export
 interface
 Person
 {

  name
: 
string

  age
?: 
number

  children
: 
Person
[
]

}

Run the CLI tool in the same folder as your project's tsconfig.json (optionally passing in paths to the files you'd like it to parse).

$ ts-auto-guard ./my-project/Person.ts

See generated files alongside your annotated files:

// my-project/Person.guard.ts


import
 {
 Person
 }
 from
 './Person'


export
 function
 isPerson
(
obj
: 
any
)
: 
obj
 is 
Person
 {

  return
 (

    typeof
 obj
 ===
 'object'
 &&

    typeof
 obj
.
name
 ===
 'string'
 &&

    (
typeof
 obj
.
age
 ===
 'undefined'
 ||
 typeof
 obj
.
age
 ===
 'number'
)
 &&

    Array
.
isArray
(
obj
.
children
)
 &&

    obj
.
children
.
every
(
e
 =>
 isPerson
(
e
)
)

  )

}

Now use in your project:

// index.ts


import
 {
 Person
 }
 from
 './Person'

import
 {
 isPerson
 }
 from
 './Person.guard'


// Loading up an (untyped) JSON file

const
 person
 =
 require
(
'./person.json'
)


if
 (
isPerson
(
person
)
)
 {

  // Can trust the type system here because the object has been verified.

  console
.
log
(
`
${
person
.
name
}
 has 
${
person
.
children
.
length
}
 child(ren)`
)

}
 else
 {

  console
.
error
(
'Invalid person.json'
)

}

Debug mode

Use debug mode to help work out why your type guards are failing in development. This will change the output type guards to log the path, expected type and value of failing guards.

$ ts-auto-guard --debug
isPerson
(
{
 name
: 
20
,
 age
: 
20
 }
)

// stderr: "person.name type mismatch, expected: string, found: 20"

Short circuiting

ts-auto-guard also supports a shortcircuit flag that will cause all guards to always return true .

$ ts-auto-guard --shortcircuit="process.env.NODE_ENV === 'production'"

This will result in the following:

// my-project/Person.guard.ts


import
 {
 Person
 }
 from
 './Person'


export
 function
 isPerson
(
obj
: 
any
)
: 
obj
 is 
Person
 {

  if
 (
process
.
env
.
NODE_ENV
 ===
 'production'
)
 {

    return
 true

  }

  return
 (

    typeof
 obj
 ===
 'object'
 &&

    // ...normal conditions

  )

}

Using the shortcircuit option in combination with uglify-js's dead_code and global_defs options will let you omit the long and complicated checks from your production code.

About

Generate type guard functions from TypeScript interfaces

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 92.2%
  • JavaScript 7.8%
- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본