最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Property 'value' does not exist on type 'EventTarget'.ts(2339) - TypeScript - Stack

programmeradmin5浏览0评论

I'm trying to use onChange function on a slider, but I keep getting and error with the Value. Am I doing something wrong ?

I'm using TypeScript and ViteJS.

My code:

      <Slider
        color="success"
        aria-label="Small steps"
        defaultValue={0.00000005}
        step={1}
        marks
        min={5}
        max={20}
        valueLabelDisplay="auto"
        value={passwordLength}
        onChange={(e) => setPasswordLength(e.target.value)}
      />

I'm trying to use onChange function on a slider, but I keep getting and error with the Value. Am I doing something wrong ?

I'm using TypeScript and ViteJS.

My code:

      <Slider
        color="success"
        aria-label="Small steps"
        defaultValue={0.00000005}
        step={1}
        marks
        min={5}
        max={20}
        valueLabelDisplay="auto"
        value={passwordLength}
        onChange={(e) => setPasswordLength(e.target.value)}
      />
Share Improve this question edited Mar 14, 2022 at 3:46 bguiz 28.4k49 gold badges163 silver badges253 bronze badges asked Mar 13, 2022 at 17:15 Cristian SuzukiCristian Suzuki 231 gold badge1 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

in TypeScript and Angular

(input)="dt.filter(getTarget($event.target).value, // other code

and

getTarget(target: EventTarget | null): HTMLInputElement {
    return target as HTMLInputElement;
  }

Looking at the error reported: Property 'value' does not exist on type 'EventTarget'

Since you are using a custom ponent <Slider>, you need to explicitly tell TypeScript the type of the HTMLElement which is your target.

Look at this for more details

You should avoid e.target, instead use e.currentTarget.

In JavaScript e.target refers to the element on which the event was fired, which may be the current element or it may be it's child. Usually for inputs you never have onChange events for children, but TypeScript doesn't know that, so it plains.

If you instead use e.currentTarget then TypeScript will know that the target is not a child element of the Slider input, so it will allow you to use e.currentTarget.value.

You can add $any to resolve the issue:

setPasswordLength($any(e.target).value)}
发布评论

评论列表(0)

  1. 暂无评论