Mashiro
Mashiro

Reputation: 1350

TS2339: Property 'xxxx' does not exist on type 'HTMLElement'

Meet this issue when I operate the DOM elements in Typescript.

I tried the most answered way on stackoverflow:

let ele: HTMLImageElement = document.getElementById("img") as HTMLImageElement

But still get the error message when compile:

enter image description here

Not sure why? Is my Typescript configuration wrong?

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "lib": ["es5", "es6", "dom"],
    "alwaysStrict": true,
    "allowSyntheticDefaultImports": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true
  }
}

Project code here: https://github.com/mashirozx/sakura2

Upvotes: 0

Views: 1228

Answers (2)

Mashiro
Mashiro

Reputation: 1350

Maybe not a good idea, but I found xxx['xxx'] works:

let ele: HTMLImageElement = document.getElementById("cover-img") as HTMLImageElement
let eleW: number = ele['naturalWidth']
console.log(eleW)

Upvotes: 0

Rich Churcher
Rich Churcher

Reputation: 7654

I think this is probably the issue (from your webpack.config.js):

      {
        test: /\.tsx?$/,
        use: [
          { loader: 'ts-loader' },
          { 
            loader: 'babel-loader',
            query: {
              presets: ['@babel/preset-typescript'],
            },
          },
        ],
        exclude: /node_modules/
      }

Typically, you'd use either ts-loader or babel-loader, not both. I note that removing either one of them from your project allows your code to run as you'd expect. Note that you can still use both together, but you'd want to take the TypeScript preset out of your Babel config I suspect.

Upvotes: 1

Related Questions