ts typescript 类型声明 特殊声明字段 数字为key 键时候处理

本文探讨了如何在JavaScript中使用动态键字,如数字和字符串,定义对象,并展示了如何处理后端返回的键不确定性。通过`NumberKey`和`StringKey`类型导出,以及`Option`对象示例,揭示了在实际开发中的应用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数字为键命名

const data :{[key: number]: string} = {
 1: 'a',
 2: 'b'
}

// data[1] = 'a'
// data[2] = 'b'

当后端返回的对象键不确定的时候

const data :{[key: string]: string} = {
 'xxx': 'a',
 'abc': 'b'
}

// data['xxx'] = 'a'
// data['abc'] = 'b'

常用类型

export type StringType = NonNullable<string | null | undefined>;
export type NumberType = NonNullable<number | null | undefined>;
export type BooleanType = NonNullable<boolean | null | undefined>;
export type StringNumberType = NonNullable<string | number | null | undefined>;
/** 以number 作为key的 */
export type NumberKey<T = any> = { [key: number]: T }
/** string 作为key的 */
export type StringKey<T = any> = { [key: string]: T }
export type Option = { label: string; value: string }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值