TypeScript联合类型 接口
<h1 id="typescript联合类型">TypeScript联合类型</h1><p>联合类型表示取值可以为多种类型中的一种<br>
如下所示</p>
<pre><code>/**
* 联合类型
*/
var muchtype:string|number="hello";
muchtype=1;
</code></pre>
<p>这一块我们必须使用string或者number都支持的类型,那么下面我们可以进行调用扩展方法toString()</p>
<pre><code>/**
* 联合类型
* 注意:如果说我们使用字符串的length属性那么我们需要注意,如果是number类型是不支持的
* 这一块我们必须使用string或者number都支持的类型,那么下面我们可以进行调用扩展方法toString()
*
*/
var muchtype:string|number="hello";
muchtype="";
muchtype=1;
console.log(muchtype.length)
console.log(muchtype.toString().length)
</code></pre>
<h1 id="typescript中对象类型-接口">TypeScript中对象类型-接口</h1>
<p>接口可以描述一种抽象的行为,也可以描述对象的结构形状,当然我们也需要遵守接口命名规范,接口一般首字母大写 当然在一些语言上面建议接口的名称前缀加上<code>I</code>前缀</p>
<pre><code>interface IStudent{
name:string
}
/**
* 接口规范了name属性是必须要写的所以我们要通过第四行代码进行使用
* 接口起到一个约束作用约束我们这些属性字段必须一对一的编写.
*/
var obj1:IStudent;
obj1="11";
obj1=1;
obj1={name:"11"};
</code></pre>
<p>如果说我们进行修改接口如下所示</p>
<pre><code>interface IStudent{
name:string,
age:number
}
</code></pre>
<p>那么我们必须要给age进行赋值操作</p>
<pre><code>obj1={name:"11",age:1};
</code></pre>
<p><strong>可选类型nullable</strong></p>
<pre><code>interface IStudent
{
name:string,
age?:number //?为一个可空类型nullable 他是一个可有可无的,那么在下面我们可以不用对age进行赋值操作也不会出现异常
}
var obj2={name:"张三",age:1}
</code></pre>
<p>在我们属性不确定的时候我们可以通过如下方式实现,any必须是任意类型,<br>
因为当我们进行使用不确定属性个数的时候会有局限性.<br>
当然下面的属性中比如说string number我们也可以使用联合类型,这一块我们后续可以根据实际需求进行变动即可</p>
<pre><code>//属性个数不确定的时候
interface IStudent{
name:string,
age?:number,
:any
}
var obj3:IStudent={name:"Mr.A",age:1,sex:"男",birthday:"2020-03-20"}
</code></pre>
<p>只读属性 <strong>readonly</strong></p>
<pre><code>interface IStudent{
name:string,
readonly age:number
}
var obj3:IStudent={name:"Mr.A",age:18}
obj3.name="Mr.B";
obj3.age=19;
</code></pre>
<p>通过如上代码我们可以发现当我们对obj3.age进行赋值的时候会发现感知错误提示 如下所示</p>
<p><img src="https://imgkr.cn-bj.ufileos.com/3c8688df-6ab6-4e11-9e31-c01dad38eff9.png" alt="" loading="lazy"></p>
<p>也就是说一旦我们赋初始值以后那么后面我们就不能将其进行修改了.</p><br><br>
来源:https://www.cnblogs.com/yyfh/p/12684209.html
頁:
[1]