在 TypeScript 中, typeof 操作符可以用来获取一个变量或工具的类型。
interface Person {
name: string;
age: number;
}
const sem: Person = { name: "semlinker", age: 30 };
type Sem = typeof sem; // type Sem = Person
在上面代码中,我们通过 typeof 操作符获取 sem 变量的类型并赋值给 Sem 类型变量,之后我们就可以使用 Sem 类型:
const lolo: Sem = { name: "lolo", age: 5 }
你也可以对嵌套工具执行相同的操作:
const kakuqo = {
name: "kakuqo",
age: 30,
address: {
province: '福建',
city: '厦门'
}
}
type Kakuqo = typeof kakuqo;
/*
type Kakuqo = {
name: string;
age: number;
address: {
province: string;
city: string;
};
}
*/
此外, typeof 操作符除了可以获取工具的结构类型之外,它也可以用来获取函数工具的类型,好比:
function toArray(x: number): Array<number> {
return [x];
}
type Func = typeof toArray; // -> (x: number) => number[]
TypeScript 3.4 引入了一种新的字面量组织方式,也称为 const 断言。当我们使用 const 断言组织新的字面量表达式时,我们可以向编程语言发出以下信号:
readonly readonly
下面我们来举一个 const 断言的例子:
let x = "hello" as const;
type X = typeof x; // type X = "hello"
let y = [10, 20] as const;
type Y = typeof y; // type Y = readonly [10, 20]
let z = { text: "hello" } as const;
type Z = typeof z; // let z: { readonly text: "hello"; }
数组字面量应用 const 断言后,它将酿成 readonly 米组,之后我们还可以通过 typeof 操作符获取米组中米素值的团结类型,详细如下:
type Data = typeof y[number]; // type Data = 10 | 20
这同样适用于包罗引用类型的数组,好比包罗通俗的工具的数组。这里我们也来举一个详细的例子:
const locales = [
{
locale: "zh-CN",
language: "中文"
},
{
locale: "en",
language: "English"
}
] as const;
// type Locale = "zh-CN" | "en"
type Locale = typeof locales[number]["locale"];
另外在使用 const 断言的时刻,我们还需要注意以下两个注意事项:
const 断言只适用于简朴的字面量表达式
// A 'const' assertions can only be applied to references to enum members,
// or string, number, boolean, array, or object literals.
let a = (Math.random() < 0.5 ? 0 : 1) as const; // error
let b = Math.random() < 0.5 ? 0 as const :
1 as const;
const 上下文不会立即将表达式转换为完全不可变
let arr = [1, 2, 3, 4];
let foo = {
name: "foo",
contents: arr,
} as const;
foo.name = "bar"; // error!
foo.contents = []; // error!
foo.contents.push(5); // ...works!
在 TypeScript 中, typeof 操作符可以用来获取一个变量或工具的类型。而 keyof 操作符可以用于获取某种类型的所有键,其返回类型是团结类型。领会完 typeof 和 keyof 操作符的作用,我们来举个例子,先容一下它们若何连系在一起使用:
const COLORS = {
red: 'red',
blue: 'blue'
}
// 首先通过typeof操作符获取Colors变量的类型,然后通过keyof操作符获取该类型的所有键,
// 即字符串字面量团结类型 'red' | 'blue'
type Colors = keyof typeof COLORS
let color: Colors;
color = 'red' // Ok
color = 'blue' // Ok
// Type '"yellow"' is not assignable to type '"red" | "blue"'.
color = 'yellow' // Error
1.阿里云: 本站现在使用的是阿里云主机,平安/可靠/稳固。点击领取2000米代金券、领会最新阿里云产物的种种优惠流动点击进入
2.腾讯云: 提供云服务器、云数据库、云存储、视频与CDN、域名等服务。腾讯云各种产物的最新流动,优惠券领取点击进入
3.广告同盟: 整理了现在主流的广告同盟平台,若是你有流量,可以作为参考选择适合你的平台点击进入
链接: http://www.fly63.com/article/detial/8164