【问题标题】:How to use imported namespace as a typescript interface?如何使用导入的命名空间作为打字稿接口?
【发布时间】: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


【解决方案1】:

FooBar 是值。 typeof operator 可以用来获取他们的类型:

type MyTypes = keyof typeof Foo;

type MyType = {
  [typeName in MyTypes]: keyof typeof Bar;
};

// Or just:
// type MyType = Record<MyTypes, keyof typeof Bar>

typeof 运算符可以在类型上下文中用于引用变量或属性的类型

不确定这是否是您要查找的内容,但在这种情况下,MyType 将解析为:

{
  ObjA: "stringA" | "stringB";
  ObjB: "stringA" | "stringB";
}

【讨论】:

  • 啊,我从未见过keyof typeof 组合!虽然它似乎只对 Foo 有效。 keyof Bar 抛出“Bar 引用一个值,但被用作类型。你的意思是 typeof 吗?”,类型定义是“字符串 | 数字 | 符号”。可能是因为它的导入方式?
  • 这是一个关于代码框codesandbox.io/s/green-platform-xrent?file=/src/index.ts的示例
  • 啊,这是因为 Bar 已有 Bar: { [key: string]: string } 的定义。我更新了示例并分叉了沙包codesandbox.io/s/modern-resonance-v9ruk。它奇怪地使 MyType 值解析为字符串 |号码
  • 好吧,您需要删除显式类型,因为它会覆盖推断值
  • 那不是我的代码,所以我无法删除它:/
猜你喜欢
  • 1970-01-01
  • 2020-06-30
  • 2016-07-24
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 2019-03-04
相关资源
最近更新 更多