Max*_*ber 7 type-declaration typescript
在这种情况下{ compilerOptions: {declaration: true }},我在 tsconfig.json 中使用 TS 3.9 时出现以下错误:
// a.ts
export const key = 1234
export const obj = {
[key]: 1
};
export default obj;
// b.ts
import A from "./a";
import { key} from "./a"
// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)
const theExport = {
A: A,
B: 2,
C: 3,
};
export default theExport
Run Code Online (Sandbox Code Playgroud)
// Exported variable 'theExport' has or is using name 'key' from external module "c:/tsexample/src/a" but cannot be named.ts(4023)
Run Code Online (Sandbox Code Playgroud)
在对相关问题的评论中,当时 TS 的 PM 提出了两种解决方法:
(1) 在这种情况下不起作用。我尝试从“a”导出所有内容并在“b”中导入所有内容,错误消息没有区别。
唯一有效的是这种非常冗长且难以维护的显式类型注释:
// updated b.ts
import A from "./a";
const theExport: {
// https://github.com/microsoft/TypeScript/issues/9944
[index: string]: typeof A | number;
} = {
A: A,
B: 2,
C: 3,
};
export default theExport;
Run Code Online (Sandbox Code Playgroud)
我的问题是:
这个问题与以下问题相似但不同:
它不是那么漂亮,但这是一个微创的改变,似乎在沙箱中工作:
const theExport = {
A: A as {[K in keyof typeof A]: typeof A[K]},
B: 2,
C: 3
};
Run Code Online (Sandbox Code Playgroud)
根据此评论,看起来一个解决方案可能是:
// a.ts
export const key = 1234
export const obj = {
[key]: 1
};
export default obj;
// b.ts
import A from "./a";
interface ITheExport {
A: typeof A;
B: number;
C: number;
}
const theExport: ITheExport = { // strong typing the object instead of using inference
A: A,
B: 2,
C: 3,
};
export default theExport
Run Code Online (Sandbox Code Playgroud)
参见沙箱
| 归档时间: |
|
| 查看次数: |
928 次 |
| 最近记录: |