typescript中type和interface有什么区别?
概念:
interface:接口,主要用于定义【对象类型】,可以对【对象】的形状进行描述。
type :类型别名,为类型创建一个新名称。它并不是一个类型,只是一个别名。
// interface
interface Form {
username: string
account: string
readonly phone: number // 只读属性
email: string | number // 联合类型
status?: string // 可选属性
}
// 接口可以通过extends实现接口扩展
interface Automobile {
name: string | null
}
// 接口继承
interface AUDI extends Automobile {
wheel: number | null
}
// 声明AUDI的实例,此时AUDI继承了一个新的属性
const audo: AUDI = {
name: 'BMW',
wheel: 4
}
// 总结:接口interface可以实现继承扩展合并,定义复杂的对象类型
type
定义基本类型别名,如 type StringType = string
声明联合类型,如 type ParamType = number | string
声明元组类型,如 type ArrType = [string, string, number]
// type 未关键字,Info 未类型别名,一般首字母大写
type Info = {
name: string
age: number
address: string
}
typescript中null和undefined是什么类型?
TypeScript 里,undefined 和 null 两者各自有自己的类型分别叫做 undefined 和 null。 它们的本身的类型用处不是很大:
let nane: undefined = undefined
let age: null = null
默认情况下 null 和 undefined 是所有类型的子类型。 就是说你可以把 null 和 undefined 赋值给 number 类型的变量。
ts中什么是联合类型?
联合类型(Union Types),表示取值可以为多种类型中的一种。使用 | 分隔每个类型。
此处的 number | string 的含义是,允许param的类型是 number 或者 string 中的一种或者多种,但不能是其他类型
typescript中const vs readonly
最简单判断该用 readonly 还是 const 的方法是看要把它做为变量使用还是做为一个属性。
做为变量使用的话用 const,若做为属性则使用 readonly。
元组Tuple和数组Array有什么区别?
在 TS 中,元组表示 这个数组有不同的类型 。简单的一句话来表述,如果类型相同的一组数据就是数组,反之就是元组;数组的 api 对于元组来讲也是通用的(push、pop等),只是类型不同
// 声明一个元组类型
let x: [string, number];
// 初始化元组
x = ['hello', 10]; // OK
// 错误的初始化类型
x = [10, 'hello']; // Error
数组:
// 声明数组的方式有两种:
// 第一种,可以在元素类型后面接上 [],表示由此类型元素组成的一个数组:
let list: number[] = [1, 2, 3];
// 第二种方式是使用数组泛型,Array<元素类型>:
let list: Array<number> = [1, 2, 3];