【学习笔记】TypeScript typeof 操作符

【学习笔记】TypeScript typeof 操作符

原文:http://www.semlinker.com/ts-typeof/

 

 

在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[]

 

posted on   独自去流浪  阅读(5483)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示