打字稿图像导入 [英] Typescript image import
本文介绍了打字稿图像导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里找到了解决方案: Webpack&打字稿图像导入
I found a solution here: Webpack & Typescript image import
但是我对此有误:
[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'.
我想我需要以某种方式强制导入,但无法弄清楚如何.
我在React中做到这一点.我看到src
属性定义为string | undefined
,这就是为什么弹出错误的原因.
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.
这是代码:
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"]
}
推荐答案
摆脱该错误的一种方法是通过如下修改d.ts文件:
One of the ways to get rid of that error is by modifying d.ts file as follows:
declare module "*.png"
删除
{
const value: string;
export default value;
}
或者您可以执行以下操作:
or alternatively you can do:
declare module "*.png" {
const value: any;
export default value;
}
更新
使用类型检查的最佳解决方案是:
The best solution with type-checking is:
declare module "*.png" {
const value: any;
export = value;
}
这篇关于打字稿图像导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文