// Compiled with --strictNullChecksfunctionvalidateEntity(e?:Entity) {// Throw exception if e is null or invalid entity}functionprocessEntity(e?:Entity) {validateEntity(e);let a =e.name; // TS ERROR: e may be null.let b = e!.name; // OKAY. We are asserting that e is non-null.}
classC { foo:number; // OKAY as assigned in constructor bar:string="hello"; // OKAY as has property initializer baz:boolean; // TS ERROR: Property 'baz' has no initializer and is not assigned directly in the constructor.constructor() {this.foo =42; }}
classC { foo!:number;// ^// Notice this exclamation point!// This is the "definite assignment assertion" modifier.constructor() {this.initialize(); }initialize() {this.foo =0; }}
単純な変数宣言でこのアサーションを使用することもできます(例:
let a:number[]; // No assertionlet b!:number[]; // Assertinitialize();a.push(4); // TS ERROR: variable used before assignmentb.push(4); // OKAY: because of the assertionfunctioninitialize() { a = [0,1,2,3]; b = [0,1,2,3];}