TypeScript相关问题及知识点
Q1: ts中type和interface的区别?
A1: 有相同点与不同点,具体内容如下。
1. 相同点:
(1) 两者都可以定义对象和函数。
interface:
interface Person{
name: string;
age: number;
}
interface SetPerson {
(name: string, age: number): void;
}
type:
type Person= {
name: string;
age: number
};
type SetPerson = (name: string, age: number)=> void;
(2)interface 定义的对象用extends继承,type用&进行复用。
interface:
interface Person{
name: string;
age: number;
}
interface Student extends Person{
class: string;
}
type:
type Person= {
name: string;
age: number
};
type Student = Person & {class: string};
2. 不同点:
(1)interface可以重复声明并且可合并,即声明了多个同样名称的接口可以合并成一个,而type不行。
interface Pesron{
name: string;
age: number;
}
interface Person{
sex: string;
}
/*
Person接口为 {
name: string;
age: number;
sex: string ;
}
*/
(2) type可以声明:基本类型的别名、联合类型、元组等类型,而interface不行。
// 别名
type Empty=null;
// 联合类型
interface Person1{
sayHi();
}
interface Person2{
eat();
}
type Person = Person1 | Person2;
type ex = number | string;
// 元组 数组中元素的数据类型都一般是相同的(any[] 类型的数组可以不同),如果存储的元素数据类型不同,则需要使用元组。
type tuple=[1,'good'];
//type 语句中可以使用 typeof 获取实例的类型进行赋值
let tem = new Number();
type B = typeof tem;
(3)还有其他复杂操作,泛型等。
Q2: ts中interface和class的区别? 分别什么时候使用?
A2: interface和class都能定义数据模型。区别:……
区别:interface只是用来声明对象类型或方法,不做实现;而class是类的声明并实现。
- 简单的数据模型,直接用于展示的,用 interface 进行定义;
- 比较复杂的数据模型,有字段属性定义以及一些方法,就需要使用 class 。里面还有
constructor构造函数。 - interface 只在编译时用于类型检查,class 编译完成之后实际上就是 javascript 中的原型(prototype)。
接口可以通过
extends继承类,类可以通过implements去实现接口。有个很好的例子帮助理解。
Q3: ts中的泛型有什么了解?
A3: 案例
1. 不用泛型的话,这个函数可能是下面这样:
function identity(arg: number): number {
return arg;
}
或者,我们使用any类型来定义函数:
function identity(arg: any): any {
return arg;
}
any的情况,可以是任何类型。因此,我们需要一种方法使返回值的类型与传入参数的类型是相同的。 这时,就用到了T,类型变量,它是一种特殊的变量,只用于表示类型而不是值。
function identity<T>(arg: T): T {
return arg;
}
这样就可以跟踪函数里使用的类型信息。
2. 泛型的使用方法有两种:
此处参考官方文档改写。
(1) 尖括号的形式:
let output = identity< string> ("myString");// type of output will be 'string'
这里明确的指定了T是string类型,并做为一个参数传给函数,使用了<>括起来。
(2) 利用了类型推论,即编译器会根据传入的参数自动地帮助我们确定T的类型:
let output = identity("myString"); // type of output will be 'string'
Q4: Typescript中如何复用属性?
A3: 可以用Omit 和 Pick,具体如下:
Omit用于排除类型中的属性,Pick用于选择类型中的属性。
Omit的使用:
interface Props {
a: string;
b: string;
c: string;
}
interface Props1 extends Omit<Props, 'c'> {
e: string;
}
以上代码做的是保留Props中的a,b属性,排除c属性, 得到结果是 a,b,e:
interface Props {
a: string;
b: string;
c: string;
}
interface Props1 {
a: string;
b: string;
e: string;
}
以上效果也可以用Pick实现,选择Props中的 a,b:
interface Props {
a: string;
b: string;
c: string;
}
interface Props1 extends Pick<Props, 'a' | 'b'> {
e: string;
}
例如,假设有一个类型 Person:
type Person = {
name: string;
age: number;
gender: string;
};
我们可以使用 Pick 来选择 Person 类型中的部分属性,比如只选择 name 和 age 属性,忽略了 gender 属性:
type SelectedPerson = Pick<Person, 'name' | 'age'>;
关于Pick的更多内容参考文章:juejin.cn/post/727526…
特别声明:本人于与CSDN博客清颖(aaqingying为同一人)
我的博客链接:blog.csdn.net/aaqingying
本文为原创文章,转载请注明出处。