如何从类型对象中动态删除键?
例如,我的接口(interface)QUERY_PARAMS
是:
export interface QUERY_PARAMS {
query: string;
min_height?: string;
max_height?: string;
min_width?: string;
max_width?: string;
color?: string;
image_type?: IMAGETYPE;
order?: ORDER;
orientation?: ORIENTATION;
}
我尝试动态删除键的代码:
async getAllImages(inputParams: QUERY_PARAMS) {
for (let key in inputParams) {
if (!inputParams[key]) {
delete inputParams[key]
}
}
// ...
}
它抛出错误:
element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'QUERY_PARAMS'. No index signature with a parameter of type 'string' was found on type 'QUERY_PARAMS'
最佳答案
该错误是因为 key
是一个字符串,它不够具体,无法作为 inputParams
的属性,即 keyof QUERY_PARAMS
。目前 TS 不允许您为 for
循环 ( issue#3500 ) 的迭代变量定义类型,但您可以对循环内的键执行类型断言:
export interface QUERY_PARAMS {
query: string;
min_height?: string;
// ...
}
async function getAllImages(inputParams: QUERY_PARAMS) {
for (let key in inputParams) {
const k = key as keyof QUERY_PARAMS; // <-- type assertion
if (!inputParams[k]) {
delete inputParams[k]
}
}
// ...
}
const p: QUERY_PARAMS = {
query: 's',
min_height: undefined,
}
console.log(p); // { query: 's', min_height: undefined }
getAllImages(p);
console.log(p); // { query: 's' }
关于typescript - 如何从 TypeScript 中的类型化对象中动态删除键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63429072/