如何让typescript知道通过索引签名定义的对象解构后具有哪些键?
问题描述
我使用索引签名以及Record<key,type>定义了DictionaryMap类型,但解构DictionaryMap类型的值被typescript告知值中不存在XX属性,我该如何让typescript知道这个值中有这个XX属性呢?
具体代码
类型定义
export type SceneType = 'session' | 'theme';export interface DictionaryMap {
[key: string]: (
| {
label: string;
value: string;
}
| undefined
)[];
}
export type DictionaryState = Record<SceneType, DictionaryMap>;
pinia中定义DictionaryState类型变量
typescript">import { DictionaryMap, DictionaryState, SceneType } from '@/types/dictionary';import { defineStore } from 'pinia';
const useDictionaryStore = defineStore('dictionary', {
state: (): DictionaryState => ({
theme: {
name: [
{
label: '消逝的光芒',
value: 'XiaoShiDeGuangMang'
},
{
label: '咒经',
value: 'ZhouJing'
},
{
label: '还愿',
value: 'HuanYuan'
},
{
label: '剃头',
value: 'Titou'
},
{
label: '人魅',
value: 'RenMei'
},
{
label: '血校',
value: 'XueXiao'
},
{
label: '见鬼十法',
value: 'JianGuiShiFa'
},
{
label: '疗养院',
value: 'LiaoYangYuan'
}
]
},
session: {
status: [
{
label: '拼场中',
value: '1'
},
{
label: '待开场',
value: '2'
},
{
label: '已开场',
value: '3'
},
{
label: '已结束',
value: '4'
}
]
}
}),
actions: {
getDictionary(key: SceneType): DictionaryMap {
return this.$state[key];
}
}
});
export default useDictionaryStore;
封装hook
import { useDictionaryStore } from '@/store';import { DictionaryMap, SceneType } from '@/types/dictionary';
const dictionaryStore = useDictionaryStore();
export default function useDictionary(scene: SceneType) {
const dictionary = dictionaryStore.getDictionary(scene) as DictionaryMap;
const getDictionaryMap = (dictionaryKey: keyof typeof dictionary, value: string) => {
const dictionaryArray = dictionary[dictionaryKey];
return dictionaryArray.find((item) => item?.value === value)?.label || '--';
};
return {
getDictionaryMap,
...dictionary
};
}
调用hook
const { status, getDictionaryMap } = useDictionary('session');
回答:
问题出现在这,可以试试:
return ({ getDictionaryMap,
...dictionary
}) as (typeof getDictionaryMap & DictionaryMap)
或者写个通用泛型工具
以上是 如何让typescript知道通过索引签名定义的对象解构后具有哪些键? 的全部内容, 来源链接: utcz.com/p/932780.html