有以下interface类型:
interface IDeliveryFormError {
time?: string,
date?: string
}
如何将它转换成这样的东西:
interface IDeliveryFormError {
[key:'time']: string,
[key:'date']: string
}
但是如果值是可选的呢?那些。这样以后,当试图向名称与接口中描述的名称不同的对象推送密钥时,TS 会诅咒,但同时,如果根本不存在该密钥,它也不会诅咒。
也许我问的问题不正确,所以我会说我需要在循环中使用它for in:
for(let key in errors) {
if(errors[key]) return true
}
编译器time?: string在使用时发誓:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IDeliveryFormError'.
No index signature with a parameter of type 'string' was found on type 'IDeliveryFormError'.
如果我在接口中定义它[key:string]:string,那么一切都可以,但我想明确表示我正在等待
除了问题
在循环中,我检查第二个对象中是否有具有我需要的值的键,如果有,则返回 true
interface IErrors {
time?: string,
date?: string
}
interface ITouched {
time?: string,
date?: string
}
const isFalse = (errors:IErrors,touched:Itouched) => {
let bool = false
for(let key in errors) {
if(Object.keys(touched).includes(key) && errors[key]) bool = true
}
return bool
}
首先,索引签名不能以这种方式使用,其次,in
for..in(以及 inObject.keys和Object.entries)中的键没有类型化和推断,它们始终具有类型string。这样做是因为 TS 无法确定哪些键将在运行时出现,例如:
因此,在使用它时,
for..in必须显式地将密钥转换为所需的类型: