interface
interface Point2D {
x: number
y: number
}
interface Point3D extends Point2D {// 继承
z: number
}
enum
enum Direction {
Up,
Down,
}
const directionNum: Direction = Direction.Up// Direction.Up就是0,Direction.Down就是1,从0开始递增
type
let p = { x: 1, y: 2 }
type FromP = typeof p// 获取某个实例的类型用typeof
// type FromP = {
// x: number
// y: number
// }
readonly
class Person {
readonly age: number = 18
constructor(age: number) {// 只读属性只能在实例化的时候赋值
this.age = age
}
}
// readonly不能修饰方法,注意readonly和后续的Readonly
interface IPerson {
readonly name: string
}
let person: IPerson = {
name: 'malinshu',
}
person.name = 'malin' //不能赋值,只读
let obj: { readonly name: string } = {
name: 'malinshu',
}
obj.name = 'malin' //不能赋值,只读
&
// interface只能修饰对象,class可以implements接口
interface Person1 {
name: string
}
interface Contact {
phone: string
}
type PersonDetail = Person1 & Contact// 合并类型
let obj1: PersonDetail = {
name: 'malinshu',
phone: '189',
}
Readonly
interface Props {
id: string
children: number[]
}
type ReadonlyType = Readonly<Props>// 创建一个只读对象类型
let props: ReadonlyType = { id: '1', children: [1] }
props.id = '0' // 不能赋值,只读
Pick
interface Props {
id: string
title: string
}
type PickProps = Pick<Props, 'id'>
// type PickProps = {
// id: string
// }
Record
type RecordObj = Record<'a' | 'b', string>// 等同下,相当于刻录一个对象类型RecordObj出来
// type RecordObj = {
// a: string
// b: string
// }
[key]: value
interface AnyObj {
[key: string]: number// 高级用法[key in keyof Props1],如下
}
type PropKeys = 'x' | 'y'
type Type2 = {
[key in PropKeys]: number
}
type Props1 = {
a: number
b: number
}
type Type3 = {
[key in keyof Props1]: number// 注意对比一下泛型,这里用in,而泛型用extends,如文章结尾
}
type Porps = {
a: number
b: string
c: boolean
}
type Type4 = Porps['a' | 'b'] // 其实也就相当于pick
// type Type4 = string | number
type TypeA = Porps[keyof Porps]
// type TypeA = string | number | boolean
泛型
type PropsFun = {
a: number
b: string
}
type FunType = <K extends keyof PropsFun>(param: PropsFun[K]) => PropsFun[K]
const Fun: FunType = (value) => {
return value
}
console.log('consoleconsole', Fun(110))
console.log('consoleconsole', Fun('string'))
版权声明:本文为weixin_41254345原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。