收到错误后,unions can't be used in index signatures, use a mapped object type instead
我现在尝试将字符串文字联合(接口的键名)转换为映射对象,如此处所述。https://github.com/microsoft/TypeScript/issues/24220#issuecomment-390063153
但它仍然无法正常工作:
const returnObject: {
[index : mappedObjectOfConfigDataKeys] : Partial<ConfigData>
} = {...accumulator};
// error TS1023: An index signature parameter type must be either 'string' or 'number'.
// 51 [index : // mappedObjectOfConfigDataKeys] : // Partial<ConfigData>
// ~~~~~
if (currentStepInstance.hasSaveableData && currentStepInstance.configDataKey) {
returnObject[currentStepInstance.configDataKey] = validatedUserInput;
}
// error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
// No index signature with a parameter of type 'string' was found on type '{}'.
// 55 returnObject[currentStepInstance.configDataKey] = validatedUserInput;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
为了证明前面的问题:
const returnObject: {
[index : stringLiteralUnion] : Partial<ConfigData>
} = {...accumulator};
// (parameter) index: stringLiteralUnion
// An index signature parameter type cannot be a union type. Consider using a mapped object type instead.ts(1337)
有人知道怎么修这个东西吗?这最后两次尝试让我陷入了困境。编译器似乎希望映射对象传递一组受约束的字符串;我不知道如何以可接受的方式给予它。
export default interface ConfigData {
languageCode : string
, numberOfRepeats : number
, projectId : string
}
/**** Index Signature handling for the above interface ****/
export type stringLiteralUnion = "languageCode" | "numberOfRepeats" | "projectId";
export type mappedObjectOfConfigDataKeys = {[key in stringLiteralUnion]: string};
// also tried typing it as `any` as shown in the linked post
// same error occured
打字稿游乐场
更新 1
尝试:
const returnObject: Record<keyof ConfigData, Partial<ConfigData>> = {...accumulator};
错误信息:
const returnObject: Record<"languageCode" | "numberOfRepeats" | "projectId", Partial<ConfigData>>
Type '{ languageCode?: string | undefined; numberOfRepeats?: number | undefined; projectId?: string | undefined; }' is not assignable to type 'Record<"languageCode" | "numberOfRepeats" | "projectId", Partial<ConfigData>>'.
Types of property 'languageCode' are incompatible.
Type 'string | undefined' is not assignable to type 'Partial<ConfigData>'.
Type 'undefined' is not assignable to type 'Partial<ConfigData>'.ts(2322)
更新 2
尝试:
const returnObject: Record<"languageCode" | "numberOfRepeats" | "projectId", Partial<ConfigData>> = {...accumulator};
错误:
const returnObject: Record<"languageCode" | "numberOfRepeats" | "projectId", Partial<ConfigData>>
Type '{ languageCode?: string | undefined; numberOfRepeats?: number | undefined; projectId?: string | undefined; }' is not assignable to type 'Record<"languageCode" | "numberOfRepeats" | "projectId", Partial<ConfigData>>'.
Types of property 'languageCode' are incompatible.
Type 'string | undefined' is not assignable to type 'Partial<ConfigData>'.
Type 'undefined' is not assignable to type 'Partial<ConfigData>'.ts(2322)