项目作者: micronova-dev

项目描述 :
Type-safe nested property accessor for Typescript
高级语言: TypeScript
项目地址: git://github.com/micronova-dev/typed-get.git
创建时间: 2019-05-30T00:12:02Z
项目社区:https://github.com/micronova-dev/typed-get

开源协议:

下载


typed-get

Type-safe nested property accessor for Typescript

Note there is a newer generic version available.

Installation

To install:

  1. yarn add micronova-dev/typed-get

Usage

In order to use typed-get:

  1. import get from "typed-get";

Then for an object x, the following expression:

  1. get(x, "p", "q")

returns the value of x.p.q if “available”, otherwise undefined. Here “available” means that:

  • x is not “nullable” (null or undefined);
  • “p” is a valid property of x;
  • x.p is not “nullable” (null or undefined);
  • “q” is a valid property of x.p.
  • the value x.p.q is not “nullable” (null or undefined)

The type of the expression above is the type of x.p.q when “available”, otherwise undefined or the type of x.p.q when “available” (so get() never returns null).

Array index is also supported, but indexed values are always assumed to be possibly undefined.

Please note that get() supports only up to 5 levels of nested properties (get(x, k1, k2, k3, k4, k5)).

Examples

Given this:

  1. interface U {
  2. a?: string;
  3. b: number;
  4. }
  5. interface X {
  6. p: string;
  7. u: U | null,
  8. u0: U,
  9. uu: U[]
  10. }
  11. const x: X = {
  12. p: "P",
  13. u: null,
  14. u0: {
  15. b: 6
  16. },
  17. uu: [
  18. {
  19. b: 3
  20. },
  21. {
  22. a: "A",
  23. b: 4
  24. }
  25. ]
  26. }

then:

expression type value
get(x, “p”) string “P”
get(x, “u”) U \ undefined undefined
get(x, “u”, “a”) string \ undefined undefined
get(x, “u”, “b”) number \ undefined undefined
get(x, “u0”, “a”) string \ undefined undefined
get(x, “u0”, “b”) number 6
get(x, “uu”, 1, “a”) string \ undefined “A”
get(x, “uu”, 1, “b”) number \ undefined 4