TypeScript学习笔记 (2、Object、object、{}区别;接口和对象类别)

240 阅读2分钟

Object object {}

Object object {}三者的区别

// Object(首字母大写)是 TypeScript 中的预定义类型。它是所有对象类型的基类,包括普通对象、函数、数组等。let a:Object = 123let a1:Object = '123'let a2:Object = []
​
let a3:Object = {}
​
let a4:Object = () => 213// object这个东西常用于泛型约束
// 它表示非原始类型(即除了 number、string、boolean、symbol、null 和 undefined 之外的类型)let b:object = '123' // 错误 原始类型
let b1:object = 123 // 错误 原始类型
let b2:object = false // 错误 原始类型
let b3:object = [] // 正确 数组
let b4:object = {} // 正确 对象
let b5:object = () => 123 // 正确 函数// {} new Object 其实支持所有的类型
let c:{} = 123 
let c1:{} = '123'
let c2:{} = []
let c3:{} = {name:1}  
​
// 虽然可以赋值任意类型,但是赋完值之后,是没法进行修改的let aa:{} = {name:1}
aa.age = 2

接口和对象类型

在ts中,我们定义对象的方式要用关键字interface(接口),即让数据的结构满足约束的格式:

// interface 重名 重合interface Axx{
    name:string,
    age:number
}
​
// 若遇到重名即内的定义会合并
interface Axx{
    ikun:string
}
​
interface Axx{
    name:string,
    age:number
    ikun:string 
}
​
// interface 任意keyinterface Axx{
    name:string,
    age:number
    ikun:string
    // 任意key
    [propName:string]:any
}
​
​
​
let a:Axx = {
    name:"xiaohuang",
    age:88,
    ikun:"qwer",
    a:1,
    v:2,
}
​
// interface ? readonly
//1
interface Axx{
    name:string,
    age?:number
}
​
let a:Axx = {
    name:"123",
}
​
//2 适用场合:函数、返回的关键值如id
interface Axx{
    name:string,
    age?:number
    readonly id:number
    readonly cb:()=>boolean
}
​
let a:Axx = {
    id:1,
    name:"123",
    age:88,
    cb:()=>{
        return false
    }
}
​
a.cb()
​
// 你不行让这个值变化可以加个readonly
a.cb = ()=>{
    return true
}
​
​
// interface 接口继承interface Axx1 extends B{
    name:string,
    age?:number
    readonly id:number
    readonly cb:()=>boolean
}
interface B{
    xxx:string
}
​
​
// interface 定义函数类型interface Fn{
    (name:string):number[]
}
​
const fn:Fn = function(){
    return [2]
}
​
const fn1:Fn = function(name:number){
    return [2]
}
​
// 不能多属性 也不能少属性