TypeScript

TSConfig and TS Project

  • exclude only excludes what is included with include
  • Directory entries that start with . are ignored, unless explicitly included.
  • Running tsc --listFiles will show files in the project. The are either explicitly included, or they are imported by a module.
  • A TS project cannot contain non-standard files such as .vue files.

Type System

Philosophy

Having useful error information, if errors are about to happen, make them as close to the original place that caused the issue as possible, except only in the call sites.

  • Structural instead of nominal
  • Interfaces are open and can be augmented, this change will take place globally.
  • Interfaces can be implemented and extended. Classes can also be implemented (the static side of it)
  • Interface registry pattern with module declaration.
  • void type
    • In function decoration, it means “return nothing” and must be satisfied
    • In type definition, it means “I don’t care about the return”
  • Function overloading is possible with function heads
  • static block for class setup
  • Private fields can be shared among instances, #prop prop name
  • constructor(public name: string, ...) syntactic sugar
  • override keyword for overriding function in base class
  • Type guards and narrowing. instanceof, typeof.
    • function isCarLike(val: any): val is CarLike, which returns a boolean for test results.
    • function isCarLike(val: any): asserts val is CarLike, which should throw new Error() if the test is not passed
    • Narrowing in switch: switch(true): case val instance of Bird: ...

Resources

Ecosystem

  • Zod, “TypeScript-first schema validation with static type inference”, good type support, plus zero-dependencies.
  • Yup
  • Ajv, JSON schema validator
  • Valibot, an alternative to Zod that is extremely light weight, due to modular design.
  • VeeValidate, for Vue form validation.
  • Joi

Notes

  • interface is extensible, compare this with type