// 因为接口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');
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:
1.1 Take Opposite const myFlag = !undefined
thus myFlag === true
1.2 Emphasize the property could not be empty
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');
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: