TypeScript$Concept-NullishValues

71 阅读1分钟

TypeScript$Concept-NullishValues

1.1 null

null means: there is a value, and that value is nothing.

This nothing is very much a defined value, and is certainly a presence — not an absence — of information.

const userInfo = {
  name: "Mike",
  email: "mike@example.com",
  secondaryEmail: null, // user has no secondary email
}

1.2 undefined

undefined means the value isn’t available (yet?)

interface FormInProgress {
  createdAt: Date
  data: FormData
  completedAt?: Date
}
const formInProgress: FormInProgress = {
  createdAt: new Date(),
  data: new FormData(),
}
function submitForm() {
  formInProgress.completedAt = new Date()
}

1.3 void

void should exclusively be used to describe that a function’s return value should be ignored.

console.log(`console.log returns nothing.`)
        // (method) Console.log(...data: any[]): void

2.1 Non-null assertion operator

The non-null assertion operator (!.) is used to cast away the possibility that a value might be null or undefined.

Keep in mind that the value could still be null or undefined, this operator just tells TypeScript to ignore that possibility.

一般用在测试环境,生产环境可以使用 Optional chaining ?.

type GroceryCart = {
  fruits?: { name: string; qty: number }[]
  vegetables?: { name: string; qty: number }[]
}
 
const cart: GroceryCart = {}
 
cart.fruits.push({ name: "kumkuat", qty: 1 })
// 'cart.fruits' is possibly 'undefined'.
       /* (property) fruits?: {
    name: string;
    qty: number;
}[] | undefined */
cart.fruits!.push({ name: "kumkuat", qty: 1 })

2.2 Definite assignment assertion

The definite assignment !: assertion is used to suppress TypeScript’s objections about a class field being used, when it can’t be proven1 that it was initialized.

因为 new Promise(resolve => {}) 里的函数是同步执行的,所以 isSetup 已经有值了,所以可以使用 isSetup!: boolean 来表示。

class ThingWithAsyncSetup {
  setupPromise: Promise<any> 
  isSetup: boolean // isSetup!: boolean
// error. Property 'isSetup' has no initializer and is not definitely assigned in the constructor.
 
  constructor() {
    this.setupPromise = new Promise((resolve) => {
      this.isSetup = false
      return this.doSetup(resolve)
    }).then(() => {
      this.isSetup = true
    })
  }
 
  private async doSetup(resolve: (value: unknown) => void) {
    // some async stuff
  }
}
let myThing = new ThingWithAsyncSetup()
myThing.isSetup // what if this isn't assigned yet?
          // (property) ThingWithAsyncSetup.isSetup: boolean

3.1 Optional chaining ?.

JavaScript 的知识。JavaScriptOptionlaChaining

3.2 Nullish coalescing ??

JavaScript 的知识。JavaScriptNullishCoalescing

Links

NullishValues