xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js Object key type & TypeScript All In One

js Object key type & TypeScript All In One

Object

  1. 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

  1. 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;
}


https://www.typescriptlang.org/play#code/C4TwDgpgBAksEFsAq5oF4oGdgCcCWAdgOZQA+UBArggEYQ5lQD2NAVhAMbCMCCOOAQxAAeAQRAA+RlQA2MgNwAoAPTKooSLHjJUUDNnzFp1Og3It2XRmJABtALrG5KtYXg4AZgI7Q+gkUgSiopu9F4+UADybJzAMATu4dAA3opQqlAAJiAEAgh4HFAA1hAg6qhptiUgAFxYuIRE9nVwiCiQSgC+wUA

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-04-23 23:32  xgqfrms  阅读(63)  评论(1编辑  收藏  举报