携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情
typeof 操作符可以用来获取一个变量或对象的类型
当我们用typeof t1的时候,可以获得变量t1的接口然后赋值给我们的type P1,在这里接口Person是等同于类型P1的。
interface Person{
name:string,
age:number
}
const t1:Person = {
name:'111',
age:11
}
type P1 = typeof t1 // type P1 = Person
const t2:P1 = {
name:'111',
age:11
}
无论是变量还是函数,都可以通过typeof获取目标本身的类型
//函数
function toArr(x:number):number[]{
return [x]
}
type a1 = typeof toArr //type a1 = (x:number) => number[]
const类型断言
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; // type z = { readonly text: "hello"; }
//const断言
let x = "hello" as const;
type X = typeof x; // type X = "hello"
let y = [10, 20,'111'] as const;
type Y = typeof y; // type Y = readonly [10, 20]
let z = { text: "hello" } as const;
type Z = typeof z; // type z = { readonly text: "hello"; }
type Data = typeof y[number]; // type Data = 10 | 20 | '111'
// 这里的number可以理解为数组的下标
用as const断言声明的变量,类似于用const的变量是不能更改指向地址的,只能
let arr = [1, 2, 3, 4];
let foo = {
name: "foo",
contents: arr,
} as const
foo.name = "bar"; // //无法分配到 "name" ,因为它是只读属性
foo.contents = []; // err 同上
foo.contents.push(5); // success 指向的是arr arr没有采用断言
下面这个i18n的例子中声明了一个locales,可以通过as const将包含对象的数组转换成只读类型,通过上面的例子,我们只需要通过数组下标的形式写入number,就可以拿到数组中的每个联合对象或者是对象中某个属性的联合类型。
const locales = [
{
locale: "zh-CN",
language: "中文"
},
{
locale: "en",
language: "English"
}
] as const;
type Locale = typeof locales[number]["locale"];//用number代替下标,获取属性
// type Locale = "zh-CN" | "en"
type Locale1 = typeof locales[number];
// type Locale1 = {
// readonly locale: "zh-CN";
// readonly language: "中文";
// } | {
// readonly locale: "en";
// readonly language: "English";
// }
对于在JS中的一些常用的写法,在ts上可能就会存在某些报错,所以ts的目的其实就是为了解决这些潜在的问题,比如prop按照这个写法是返回对象的属性,
function prop<T extends object,K extends keyof T>(obj: T, key: K) {
return obj[key];
}
type obj = {
name:string,
age:number
}
let tobj:obj = {
name:'111',
age:111
}
function prop1<T extends object , K extends keyof T>(obj:T,key:K){
return obj[key]
}
prop1(tobj,'name')
prop1(tobj,'date')//类型“"date"”的参数不能赋给类型“keyof obj”的参数
<T extends object,K extends keyof T>表示传入一个T属于object类型,传入一个K获取T的属性,这样传进来的参数就会自动去校验是否属于传入对象的属性。
这种声明方法可以有效的防止我们传入不属于对象的属性