mercredi 3 avril 2019

How to validate type "target.dataset" attribute of input tag in typescript

"dataset" attribute is always disallowed HTMLInputElement.

I searched the document of DOM types. There is no "data" or "dataset" anywhere.

Of course, it's possible to use "non-null" type likes below "variables key" in changeLoginValue.

export interface LoginForm {
    id: string;
    password: string;
    [key: string]: string;
}

export interface ILoginStore {
    loginValue: LoginForm;
    changeLoginValue(e: React.ChangeEvent<HTMLInputElement>): void;
}

class LoginStore implements ILoginStore {
    @observable loginValue: LoginForm = {
        id: '',
        password: '',
    }

    @action.bound changeLoginValue(e: React.ChangeEvent<HTMLInputElement>): void {
        const key = e.target.dataset.name!;
        this.loginValue[key] = e.target.value;
    }
}

But it seems a some tricky way in typescript and the most important thing is that it always fail to compile in jest.

my test code is

import LoginStore from './loginStore';

describe('LoginStore', () => {
    it('change id and password in loginValue', () => {
        const event = {
            target: {
                dataset: {
                    name: 'id',
                },
                value: 'abcdef',
            },
          } as React.ChangeEvent<HTMLInputElement>;
        expect(LoginStore.changeLoginValue(event)).toBe();
    })
})

It show typescript error when declare "const event":

Conversion of type '{ target: { dataset: { name: string; }; value: string; }; }' to type 'ChangeEvent' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

Type '{ target: { dataset: { name: string; }; value: string; }; }' is missing the following properties from type 'ChangeEvent': nativeEvent, currentTarget, bubbles, cancelable, and 10 more.ts(2352) ###

How to use "dataset" attribute? Do I have to make custom interface for this?

Aucun commentaire:

Enregistrer un commentaire