xp1632 / DFKI_working_log

0 stars 0 forks source link

Exclamation symbol ! in Typescript #15

Open xp1632 opened 1 year ago

xp1632 commented 1 year ago
  1. single ! ( from https://github.com/e2tox/blog/issues/9)

1.1 Take Opposite const myFlag = !undefined

Boolean(undefined) // false
Boolean(null) // false
Boolean(NaN) // false
Boolean(0) // false
Boolean("") // false

thus myFlag === true

1.2 Emphasize the property could not be empty

// 因为接口B里面name被定义为可空的值,但是实际情况是不为空的,那么我们就可以
// 通过在class里面使用!,重新强调了name这个不为空值
class A implemented B {
  name!: string
}

interface B {
  name?: string
}

1.4 Assert that this value must exist, is never undefined or empty

// 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示 // 出错 TS2532: Object is possibly 'undefined'. new Error().stack.split('\n');

// 我们确信这个字段100%出现,那么就可以添加!,强调这个字段一定存在 new Error().stack!.split('\n');

  1. double !!,
    • convert non-Boolean to Boolean,
    • empty to false, non-empty to truth

Double exclamation marks !! in TypeScript While we’re on the topic of the exclamation mark !, TypeScript also uses double exclamation marks !! to convert (also called cast) non-Boolean type values to Boolean type. Here’s an example:

const emptyStr = ''
const nonEmptyStr = 'test'

const emptyStrBool = !!emptyStr //false
const nonEmptyStrBool = !!nonEmptyStr //true