一、typeof 简介
在 TypeScript 中, typeof 操作符可以用来获取一个变量或对象的类型。
interface Person {
name: string;
age: number;
}
const sem: Person = { name: "semlinker", age: 30 };
type Sem = typeof sem;
在上面代码中,我们通过 typeof 操作符获取 sem 变量的类型并赋值给 Sem 类型变量,之后我们就可以使用 Sem 类型:
const lolo: Sem = { name: "lolo", age: 5 }
你也可以对嵌套对象执行相同的操作:
const kakuqo = {
name: "kakuqo",
age: 30,
address: {
province: '福建',
city: '厦门'
}
}
type Kakuqo = typeof kakuqo;
此外, typeof 操作符除了可以获取对象的结构类型之外,它也可以用来获取函数对象的类型,比如:
function toArray(x: number): Array<number> {
return [x];
}
type Func = typeof toArray;
二、const 断言
TypeScript 3.4 引入了一种新的字面量构造方式,也称为 const 断言。当我们使用 const 断言构造新的字面量表达式时,我们可以向编程语言发出以下信号:
readonly
readonly
下面我们来举一个 const 断言的例子:
let x = "hello" as const;
type X = typeof x;
数组字面量应用 const 断言后,它将变成 readonly 元组,之后我们还可以通过 typeof 操作符获取元组中元素值的联合类型,具体如下:
type Data = typeof y[number];
这同样适用于包含引用类型的数组,比如包含普通的对象的数组。这里我们也来举一个具体的例子:
const locales = [
{
locale: "zh-CN",
language: "中文"
},
{
locale: "en",
language: "English"
}
] as const;
另外在使用 const 断言的时候,我们还需要注意以下两个注意事项:
const 断言只适用于简单的字面量表达式
const 上下文不会立即将表达式转换为完全不可变
let arr = [1, 2, 3, 4];
let foo = {
name: "foo",
contents: arr,
} as const;
foo.name = "bar";
vi设计http://www.maiqicn.com 办公资源网站大全https://www.wode007.com
三、typeof 和 keyof 操作符
在 TypeScript 中, typeof 操作符可以用来获取一个变量或对象的类型。而 keyof 操作符可以用于获取某种类型的所有键,其返回类型是联合类型。了解完 typeof 和 keyof 操作符的作用,我们来举个例子,介绍一下它们如何结合在一起使用:
const COLORS = {
red: 'red',
blue: 'blue'
}
来源:https://www.cnblogs.com/xiaonian8/p/13744976.html |