Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"] } 
like image 663
Mario Petrovic Avatar asked Jun 29 '18 11:06

Mario Petrovic


People also ask

How do I import a image into TypeScript?

To allow image import with TypeScript, we can use declare to declare the type for image files. to declare the type for modules with the . png extension.

How do you fix the Cannot find module error with importing images in TypeScript react?

To fix the "Cannot find module" error with importing images in TypeScript React, we should declare the . jpg module in a TypeScript type definition file. declare module '*.

What is import image?

Importing an Image File. Image files can be imported into the drawing; for example, you might import a sketch or a logo graphic. The Vectorworks Design Series products have an option to create a reference to the original image file, if the original image may change, and you want to keep the imported image up to date.


2 Answers

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; } 
like image 52
Piyush Zalani Avatar answered Sep 23 '22 14:09

Piyush Zalani


For react-native

create global.d.ts file on project root folder and just add next lines there

declare module '*.png' {   const value: import('react-native').ImageSourcePropType;   export default value; } 
like image 33
Vitalii Obideiko Avatar answered Sep 21 '22 14:09

Vitalii Obideiko