首页 > 解决方案 > 如何断言导入的值是某种类型

问题描述

我正在从一个模块导入一个值 ( f),从另一个模块导入它的类型 ( F)。我怎样才能断言它f是 type F

以下丑陋是我目前所做的:

import {f} from './some-module.js';
import {F} from './types.d.ts';

const useless: {f: F} = {f};

标签: typescript

解决方案


您可以使用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

游乐场样本


推荐阅读