简体   繁体   中英

TypeScript asking to add type to key value

I've got form in my angular project. And this form contains input with image upload. So I use FormData to send the data to server. I try to use function to append form fields to FormData.

export function toFormData<T>(formValue: T) {
    const formData = new FormData();

    for (const key of Object.keys(formValue)) {
        const value = formValue[key];  <--- error here
        formData.append(key, value);
    }

    return formData;
}

sendForm() {
    const team = toFormData(this.form.value);
    this.teamService.sendTeam(team).subscribe(() => {});
}

I've got an error from ts-lint "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. No index signature with a parameter of type 'string' was found on type 'unknown'". IDE underlines formValue[key] expression. Try to add types, but it didn't help.

formValue[key] is any because T doesn't narrow types, that's fine.

To suppress this error you need to cast any to unknown like that T extends Record<string, unknown> . Now it means value has unknown type and it should be asserted first before usage of the variable.

export function toFormData<T extends Record<string, unknown>>(formValue: T) {
    const formData = new FormData();

    for (const key of Object.keys(formValue)) {
        const value = formValue[key];
        // feel free to remove Blob if it's not your case.
        if (typeof value !== 'string' && !(value instanceof Blob)) {
            continue;
        }
        formData.append(key, value);
    }

    return formData;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM