这是我参与8月更文挑战的第12天,活动详情查看:8月更文挑战
接口中的类型转换
TypeScript 提供了几种修饰符来实现一些常见的类型转换,转换完成后可以在全局生效。本章介绍下接口使用过程中的常见转换方式;
Readonly 修饰符
之前的章节中有提到过Readonly修饰符,所以我们很容易明白这个代表的是只读。我们先来看第一个例子,顺便了解下使用方式。例 :
interface Attribute {
height: string;
width: string;
}
function upDate(selector: string, attr: Readonly<Attribute>){
attr.height = '100%'
}
//"Error": Cannot assign to 'height' because it is a read-only property.
这个例子中:我们声明了一个属性接口。我们在更新方法中调用接口并添加Readonly修饰符。添加完修饰符之后意味着我们完成了对接口的类型转换:所有属性都设置为 readonly。在更新方法内的作用域内宽高属性都是不可更改的
Partial 修饰符
此修饰符表示‘可选的、部分的’;例 :
interface Attribute {
height: string;
width: string;
}
function upDate(selector: string, attr: Partial<Attribute>){}
upDate('.className', {height: "100vh"});
上例中:我们声明的属性接口中需要两个属性。我们通过关键词将原接口中的所有属性转换为可选属性(相当于在属性后面添加?),所以我们调用时只传入一个属性,并不报错。
Required 修饰符
*所需要的,这个修饰符的效果和Partial刚好相反。例: *
interface Attribute {
height?: string;
width?: string;
}
function upDate(selector: string, attr: Required<Attribute>){}
upDate('.className', {height: '100px'});
//"Error": Property 'width' is missing in type '{ height: string; }' but required in type 'Required'.
这次我们声明的Attribute接口中的属性都是可选的,但是我们通过修饰符Required将接口中的属性全部转换为必须的属性。导致调用时报错。
Record<Keys,Type>
Record映射:把Keys和Type结合起来构造一个新的接口。例 :
interface Attribute {
height: string;
width: string;
}
type Ele = 'div' | 'span' | 'input';
// const elements: Record<'div' | 'span' | 'input', Attribute> = {
const elements: Record<Ele, Attribute> = {
div: { height: '', width: '' },
span: { height: '', width: '' },
input: { height: '', width: '' }
}
解析:别名Ele中的每一项都是新类型中的key,Attribute接口是对每一项value的规范限制。(接口不再是对elements值的规范,而是对象中每一项key的规范),请细品。
Pick<Type, Keys>
“选取”:通过从Type中选取部分属性键来构造一个类型。例 :
interface Attribute {
height: string;
width: string;
border: string
}
type Attribute2 = Pick<Attribute, 'height' | 'width'>;
const divStyle: Attribute2 = {
height: '',
width: ''
}
解析:通过Pick操作符,从接口Attribute中选取了‘height’和‘width’作为新的规范,排除了未选择的‘border’。相当于是把接口改成了:
interface Attribute {
height: string;
width: string;
}
Omit<Type, Keys>
“移除操作”:通过从 Type 中选取所有属性然后删除指定的键来构造一个类型。
interface Attribute {
height: string;
width: string;
border: string
}
type Attribute2 = Omit<Attribute, 'height' | 'width'>;
const divStyle: Attribute2 = {
border: ''
}
解析:这个例子和上面的恰恰相反。通过Omit操作符,从接口Attribute中选取了所有属性,然后移除‘height’和‘width’作为新的规范,只留下了未移除的属性。相当于是把接口改成了:
interface Attribute {
border: string
}
类型转换中关于接口的转换就先介绍到这里。下次再展示其他的转换方式。