【发布时间】:2021-12-02 03:24:45
【问题描述】:
我无法弄清楚如何在打字稿界面/类型中使用导入的名称。
我有一些导出不同类型的文件...
foo.js
const ObjA = {}
const ObjB = {}
export {
ObjA,
ObjB
}
bar.js
export const Bar: { [key: string]: string } = {
stringA: 'some string',
stringB: 'some string',
}
我想导入这些文件,并使用导入的值来创建一个新的打字稿对象定义...
import * as Foo from 'foo';
import { Bar } from 'bar';
type MyTypes = keyof Foo; // this would be ObjA, ObjB
type MyType = {
[typeName in MyTypes]: keyof Bar; // this would be stringA, stringB
};
我想强制一个对象使用一个导入文件中的导出值以及另一个导出值中的值来使用键名。类似...
const newObject: MyType = {
ObjA: 'stringA', // passes
fooKey: 'stringB', // fails due to invalid key
ObjB: 'fail', // fails due to invalid value
barKey: 'randomValue', // fails due to invalid key & value
}
【问题讨论】:
-
bar.js中的示例无法编译。你的意思是像export const Bar = { stringA: 'some string', stringB: 'some string' }这样的东西吗? -
是的,对不起,我对所有示例都进行了伪编码......足以让这个想法得到理解。我会更新它以使其更清晰
标签: typescript