Reputation: 1350
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:
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
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
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