TypeScript 高级类型
类型的且运算
interface A {
a1: string
a2: string
}
interface B {
b1: number
b2: string
}
let c: A & B = {
a1: 'hi',
a2: 'hello',
b1: 2,
b2: 'a'
}
// react
const Layout: React.FunctionComponent & { Header: React.FunctionComponent } = () => {
return React.createElement('div', null, 'hi')
}
Layout.Header = () => {
return React.createElement('div', null, 'hi')
}
// 分割线
interface Layout2 extends React.FunctionComponent {
Header: React.FunctionComponent
}
const Layout2: Layout2 = () => {
return React.createElement('div', null, 'hi')
}
Layout2.Header = () => {
return React.createElement('div', null, 'hi')
}
类型的或运算
interface A {
a1: string
a2: string
}
interface B {
b1: number
b2: string
}
let c: A | B = {
a1: 'hi',
a2: 'hello',
b1: 2,
b2: 'a'
}
可以只满足A或者B,或两者同时满足。
类型别名 type
type是给已知类型取别名, interfce
type Action = {
type: 'create' | 'update',
name: string;
}
type A = Action;
const action: A = {type: 'create', name: '123'}
字面量类型 & this 类型
type Week = 'Mon' | 'Tue' | 'Wen' | 'Thu' | 'Fri' | 'Sat' | 'Sun'
interface Course {
category: 'task' | 'live'
}
let a: Course = {
category: 'live'
}
let b: Week = 'Fri'
索引类型
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
const calender = (options: CalenderOptions) => { }
interface CalenderOptions {
[K: string]: any
}
calender({
time: Date.now,
type: 'year'
})
function pluck<T, k extends keyof T>(s: T,arr: k[]):T[k][]{
const result = arr.map(i => s[i])
console.log(result)
return result
}
type Student = {
age: number,
name: string,
grade: number
}
let s: Student = {
age: 18, name: '老王', grade: 3
}
pluck(s, ['age', 'name'])
可识别联合类型
type Action = {
type: 'create',
name: string;
} | {
type: 'update',
id: number,
name: string;
};
function fn (a: Action) {
if(a.type === 'create'){
} else {
console.log(a.id)
}
}
类型可识别的前提:
- 至少有一个共有字段
- 共有字段的值是可穷举的,如1,'one'等具体值。
分类:
typescript
标签:
typescript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY