created at 2023/08/05 04:32:06
updated at 2023/08/05 04:56:32
类型保护是可执行运行时检查的一种表达式,用于确保该类型在一定的范围内。换句话说,类型保护可以保证一个字符串是一个字符串,尽管它的值也可以是一个数值。类型保护与特性检测并不是完全不同,其主要思想是尝试检测属性、方法或原型,以确定如何处理值。
in
关键字检查对象是否具有特定的属性,并使用该属性区分不同的类型。它通常返回一个布尔值,表示该属性是否存在于该对象中。它用于其缩小范围,以及检查浏览器支持。
typescript
console.log(
'h' in
{
h: 'hello',
w: 'world',
}
);
typescript
interface Admin {
id: number;
created: string;
}
interface User {
uid: number;
created: string;
}
type allUser = Admin | User;
function getUType(u: allUser) {
if ('id' in u) {
console.log("i'm admin");
} else {
console.log("i'm user");
}
}
getUType({ uid: 1, created: '2020' });
typeof
关键字typeof 用来确定变量的类型.只能确定以下类型数据: Boolean,String,Bigint,Symbol,Undefined,Function,Number
其他情况则返回
Object
typescript
function paddingLeft(value: string, padding: string | number) {
if (typeof padding === 'number') {
return Array(padding + 1).join(' ') + value;
}
if (typeof padding === 'string') {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
instanceof
关键字Instanceof 是一个内置类型守卫,可用于检查一个值是否是给定构造函数或类的实例。
typescript
interface run {
run(): string;
}
class Person implements run {
run(): string {
return 'race';
}
}
class Ainmal implements run {
run(): string {
return 'hunt';
}
}
let w: run = new Person();
if (w instanceof Person) {
//...
}
创建一个自定义类型守卫通常是使用类型守卫的强大选项。当您通过自己编写来创建自定义类型保护时,可以检查的内容没有限制。但是,如果自定义类型保护被错误地编写,它可能会带来很多错误。因此,精度是关键。
typescript
interface Necklace {
kind: string;
brand: string;
}
interface bracelet {
brand: string;
year: number;
}
type Accessory = Necklace | bracelet;
const isNecklace = (b: Accessory): b is Necklace => {
return (b as Necklace).kind !== undefined;
};
const Necklace: Accessory = { kind: 'Choker', brand: 'TASAKI' };
const bracelet: Accessory = { brand: 'Cartier', year: 2021 };
console.log(isNecklace(bracelet)); //Logs false
console.log(isNecklace(Necklace)); //Logs true
类型谓词 b 是 Necklace,这会让 TypeScript 将类型缩减为 Necklace,而不是只返回一个布尔值。
等式收缩守卫检查表达式的值。为了使两个变量相等,两个变量必须是同一类型的。如果一个变量的类型未知,但它等于另一个具有精确类型的变量,那么 Typescript 会使用该已知变量提供的信息来缩小第一个变量的类型:
typescript
function getValues(a: number | string, b: string) {
if (a === b) {
// this is where the narrowing takes place. narrowed to string
console.log(typeof a); // string
} else {
// if there is no narrowing, type remains unknown
console.log(typeof a); // number or string
}
}
//如果变量a等于变量b,那么两者必须具有相同的类型。在这种情况下,Typescript把它缩小到字符串。如果没有收缩,a的类型仍然不明确,因为它可以是数字或字符串。