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'等具体值。