typescript - 如何断言导入的值是某种类型
问题描述
我正在从一个模块导入一个值 ( f
),从另一个模块导入它的类型 ( F
)。我怎样才能断言它f
是 type F
?
以下丑陋是我目前所做的:
import {f} from './some-module.js';
import {F} from './types.d.ts';
const useless: {f: F} = {f};
解决方案
您可以使用Assert
帮助器在编译时比较两种类型:
type Assert<Expected, Actual extends Expected> = void
// let's assume, we imported `f` from './some-module.js'
const f = { a: "foo" }
// also assume import from './types.d.ts'
type F = { a: string }
type F2 = { a: number }
type AssertF = Assert<F, typeof f> // OK
type AssertF2 = Assert<F2, typeof f> // error, f not of type F2
推荐阅读
- html - 我正在尝试创建一个记忆游戏,其中一个扩展的数字列表以离子和角度显示,用户必须输入答案
- django - 如何在 Django 中覆盖“get_queryset()”
- regular-language - 这是二进制字符串的有效正则语言表达式吗?可以浓缩成更简洁的东西吗?
- javascript - Vue中的两种数据绑定:无法从子组件更新父组件
- flutter - 如何在颤动中显示 ListTile
- python-3.x - 从同一总体中抽取的随机样本交集的平均大小
- java - 在 Eclipse 中运行第一次 Spring Boot 应用程序时出现错误警告。我正在使用 JDK 14
- android - Android后台蓝牙处理:最好的方法是什么?
- ruby-on-rails - MacOS:尝试安装 Rails 时出现 Ruby LoadError
- html - 在 Safari 中固定位置时的粘性位置跳转