typescript中特殊符号(?/!)用法
<p>1. 属性或参数中使用 ?:表示该属性或参数为可选项</p><p>2. 属性或参数中使用 !:表示强制解析(告诉typescript编译器,这里一定有值),常用于vue-decorator中的@Prop</p>
<p>3. 变量后使用 !:表示类型推断排除null、undefined</p>
<p> </p>
<p>例如</p>
<div>
<div> private _options!: ChatBoxMsgItemOptions;</div>
<div> public get options(): ChatBoxMsgItemOptions {</div>
<div> return this._options;</div>
<div> }</div>
<div> </div>
<div>
<div> @property(Label)</div>
<div> labelTitle!: Label;</div>
<div> </div>
<div>
<h1>基础类型</h1>
<ul>
<li>原始类型:number,string,boolean,symbol,null或undefined</li>
<li>object表示非原始类型,使用object类型,就可以更好的表示像Object.create这样的API</li>
</ul>
<h1>null 和 undefined</h1>
<ul>
<li>默认情况下,null和undefined是所有类型的子类型。 就是说你可以把 null和undefined赋值给number或者string类型的变量</li>
</ul>
<p>strictNullChecks<br>{<br>"compilerOptions": {<br> "target": "es5",<br> "module": "commonjs",<br> "strict": true,<br> "esModuleInterop": true,<br> "skipLibCheck": true,<br> "forceConsistentCasingInFileNames": true,<br> // "strictNullChecks": true, /* Enable strict null checks. */<br>}<br><br></p>
<p>false<br>// 当strictNullChecks置为false,或者默认。ts编译器不进行null和undefined的严格检查</p>
<p>let str1: string = undefined;//success</p>
<p>let str2: string = null;//success<br><br>true<br>//当strictNullChecks置为true,null和undefined只能赋值给void和它们各自</p>
<p>let str1: string = undefined;//fail Type 'undefined' is not assignable to type 'string'.</p>
<p>let str2: string = null;//fail Type 'null' is not assignable to type 'string'.<br><br></p>
<h1>可选属性 ?</h1>
<div>
<p>【?】 表示在strictNullChecks置为true时,height?: number; 等价于 height: number | undefined;<br>interface Test {<br>height?: number;<br>width: number;<br>}</p>
<p>function testfunc(test: Test) {<br>test.height = undefined;// success<br>test.width = undefined;// fail Type 'undefined' is not assignable to type 'number'.<br>}</p>
<p>非空断言操作符 !<br>当strictNullChecks置为true时,类中的成员必须明确定义类型;【!】表示在此处告诉编译器,此成员不会为null,不会为undefined;<br>class Test1 {<br>height!: number; //success 非null 非 undefined类型</p>
<p>test() {<br> this.height = null;// fail Type 'null' is not assignable to type 'number'.<br> this.height = undefined;// fail Type 'undefined' is not assignable to type 'number'.<br>}<br>}</p>
<p><br>class Test2 {<br> height: number | undefined | null;//success 可null 可undefined类型<br>}</p>
<p> </p>
</div>
</div>
</div>
</div><br><br>
来源:https://www.cnblogs.com/cslie/p/17059390.html
頁:
[1]