typescript常用代码片段

1. 对象属性遍历

遍历方式1:使用Object.keys

const p = {
    name: 'li',
    age: 18
}

Object.keys(p).forEach((key)=>{
    console.log((p as any)[key])
});

遍历方式2:使用keyof

interface IPerson {
    name: string;
    age: number;
}

function test(opt: IPerson) {
    let key: (keyof IPerson);
    for (key in opt) {
        console.log(opt[key]);
    }
}

遍历方式3:使用Object.entries

const obj = {
    name: 'li',
    age: 18,
};

Object.entries(obj).forEach(([k, v]) => {
    console.log(k, v);
});

遍历方式4:使用for in

const obj = {
    name: 'li',
    age: 18,
};

for (let k in obj) {
    console.log((obj as any)[k]) 
}

2. 数组遍历

方法一:for…of

let array = [1, 2, 3];
for (let entity of array) {
    console.log(entity);
}


方法二: for循环

let array = [1, 2, 3];
for(let i=0; i<array.length; i++) {
    console.log(array[i])
}


方法三:forEach

let list = [1, 2, 3];
list.forEach((val, idx, array) => {
    // val: 当前值
    // idx:当前index
    // array: Array
});


方法四,every和some
因为forEach在iteration中是无法返回的,所以可以使用every和some来取代forEach。

let list = [1, 2, 3];
list.every((val, idx, array) => {
    // val: 当前值
    // idx:当前index
    // array: Array
    console.log(`val=${val}`)
    return true; // Continues
    // Return false will quit the iteration
});

3. Map嵌套定义

export class UnitSystem {
    allUnitSystem: { [key: string]: { [key: string]: string } } = {
        'SI1': {
            length: '1',
        },
        'SI2': {
            length: '2',
        }
    }
}

4. 使用keyof定义类的索引类型

keyof是索引类型查询操作符。假设T是一个类型,那么keyof T产生的类型是T的属性名称字符串字面量类型构成的联合类型。注意keyof产生的是数据类型,并非数据本身。

interface IPerson {
    name: string;
    age: number;
}
 
type P = keyof IPerson;

let a: P = "name";
let b: P = "age";
let c: P = 12;

5. 使用类类型

在工厂方法中经常会使用类类型,如下函数,第一个参数是类类型,第二个参数是构造函数的参数。new ()表面第一个参数是类类型。

const execute = (ClassName: new (...args: any[]) => Command, ...args: any[]) => void;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值