js Object key type & TypeScript All In One
js Object key type & TypeScript All In One
Object
- object
const obj = {1: 'a'};
// {1: 'a'}
obj[1];
// 'a'
obj['1'];
// 'a'
for (let key in obj) {
console.log('key =', key, typeof key);
}
// key = 1 string
for (const [i, key] of Object.entries(obj)) {
console.log('i, key =', i, key, typeof key);
}
// i, key = 1 a string
- array
const arr = [1, '2', 3];
for (const [i, key] of arr.entries()) {
console.log('i, key =', i, key, typeof key);
}
// i, key = 0 1 number
// i, key = 1 2 string
// i, key = 2 3 number
TypeScript
interface Array
// ❌ array
// const ItemType = string | number | object | array | null;
// ✅ Array<any> / any[]
type ItemType = string | number | object | Array<any> | null;
// type ItemType = string | number | object | any[] | null
// interface Array<T>
interface ObjectInterface {
// dynamic key type
[key: string]: ItemType;
}
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16184065.html
未经授权禁止转载,违者必究!