Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

reactjs - Typescript image import

I found a solution here: Webpack & Typescript image import

But i am getting error for this:

[ts]
Types of property 'src' are incompatible.
  Type 'typeof import("*.png")' is not assignable to type 'string | undefined'.
    Type 'typeof import("*.png")' is not assignable to type 'string'.

I guess i need to cast import somehow, but cant figure out how. I am doing this in React. I saw that src attribute is defined as string | undefined, that is why error is popping.

Here is code:

import * as Logo from 'assets/images/logo.png';

HTML:

<img src={Logo} alt="" />

And definition based on above mentioned solution:

declare module "*.png" {
  const value: string;
  export default value;
}

Tsconfig:

{
  "compilerOptions": {
    "baseUrl": "./",
    "jsx": "react",
    "lib": ["es5", "es6", "dom"],
    "module": "commonjs",
    "noImplicitAny": false,
    "outDir": "./dist/",
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "es5",
    "typeRoots": [
      "custom_typings"
    ]
  },
  "include": ["./src/**/*.tsx"],
  "exclude": ["dist", "build", "node_modules"]
}
question from:https://stackoverflow.com/questions/51100401/typescript-image-import

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One of the ways to get rid of that error is by modifying d.ts file as follows:

declare module "*.png"

remove

{
  const value: string;
  export default value;
}

or alternatively you can do:

declare module "*.png" {
  const value: any;
  export default value;
}

Update

The best solution with type-checking is:

declare module "*.png" {
   const value: any;
   export = value;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...