【发布时间】:2019-12-01 11:16:53
【问题描述】:
我有一个对象,其中一些值是字符串和一些数字。
我想修剪所有字符串值。
type OptionalParams = {
a?: string;
b?: string;
c?: number;
};
const optionalParams: OptionalParams = {};
const keys = Object.keys(optionalParams) as Array<keyof OptionalParams>;
keys.forEach((key: keyof OptionalParams) => {
const paramValue = optionalParams[key];
if (typeof paramValue === 'string') {
const newValue = (paramValue as string).trim();
optionalParams[key] = newValue as keyof OptionalParams;
}
});
但我得到 ts-error:
键入'"a" | "b" | "c"' 不能分配给类型 'undefined'。
类型“a”不能分配给类型“未定义”。 ts(2322)
如果我删除“c”属性,我不会得到它,但我需要它。我用typeof加了if,但是typescript看不懂。
我的 tsconfig:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./lib",
"strict": true,
"esModuleInterop": true
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]
}
【问题讨论】:
标签: javascript typescript types