![](/img/trans.png)
[英]What's the difference between export interface and export default interface in typescript declaration merging?
[英]Typescript interface for default export
我有一个非常基本的配置文件文件夹结构,如下所示:
/config
/button
/colors
/index
代码如下所示:
colors.ts
export interface Colors {
[key: string]: string,
}
export default {
black: '#111',
grey: '#999',
green: '#4c8857',
red: '#bd1414',
white: '#fff',
};
索引.ts
import colors from './colors';
export default {
button,
colors,
};
我收到以下错误:
Could not find a declaration file for module './colors'. '/xxxxx/styles/config/colors.js' implicitly has an 'any' type.
我是 Typescript 的新手,在网上找不到任何教程或示例可以清楚地解释我在这里做错了什么。
有两个问题:由于案例错误,您没有正确导入接口:
import colors from './colors';
export interface Colors {
尝试
import {Colors} from './colors';
但在这里,您只是导出“颜色”界面,而不是颜色对象。
您可能喜欢的代码如下:
export interface Colors {
[key: string]: string,
}
export const defaultColors: Colors = {
black: '#111',
grey: '#999',
green: '#4c8857',
red: '#bd1414',
white: '#fff',
};
然后导入它
import {defaultColors} from './colors'
注意:如果您对导入很困难,我强烈建议您使用像Webstorm这样的IDE,它可以自动导入正确的依赖项。
我可以建议你让Typescript为你推断出类型。 与使用[key: string]: string
定义接口相比,您可能拥有更准确的类型。
如果您不想使用default
导出,我建议您只导出以下内容:
export const Colors = {
black: '#111',
grey: '#999',
green: '#4c8857',
red: '#bd1414',
white: '#fff',
};
然后,您import { Colors } from './colors'
导入import { Colors } from './colors'
如果颜色是colors
文件中唯一/主要的东西,那么你可以继续使用default
导出,如下所示:
const colors = {
black: '#111',
grey: '#999',
green: '#4c8857',
red: '#bd1414',
white: '#fff',
};
export default colors;
然后,您import Colors from './colors'
导入import Colors from './colors'
只需创建您的 ts 文件
interface Colors {
[key: string]: string,
}
const defaultColors: Colors = {
black: '#111',
grey: '#999',
green: '#4c8857',
red: '#bd1414',
white: '#fff',
};
export default defaultColors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.