环境是vue3 + ts
function resetForm () {
// const INITIALFORM = {
// url: '',
// device: 'mobile',
// dimension: ['time', 'page'],
// }
for (const key in INITIALFORM) {
type KeyType = keyof typeof INITIALFORM
const initialValue = INITIALFORM[key as KeyType]
// ^ const initialValue: string | string[]
form[key as KeyType] = initialValue
/**
* type KeyType = "url" | "device" | "dimension"
不能将类型“string | string[]”分配给类型“string & string[]”。
不能将类型“string”分配给类型“string & string[]”。
不能将类型“string”分配给类型“string[]”
*/
}
}
问题1. form[key as KeyType] = initialValue
这里赋值会报错,知道initialValue as any
可以处理,但,不应该这样处理吧?想知道正确的处理方式。
问题2.const initialValue = INITIALFORM[key as KeyType]
、form[key as KeyType] = initialValue
两处都需要key as KeyType
,可以提升一次性处理么?
在stackoverflow看到了详细的解答,总结一下:
TS3.5
做了大版本更新,对象元素值是联合类型时,form[key] = initialValue
是不安全 的。现有解决方案,抽取函数,使用泛型。