首页 > 解决方案 > 如何使用未使用的接口

问题描述

我正在使用noUnusedLocals打开的打字稿并且不想将其关闭。

但现在我正在尝试应用某种附加断言,如下所述

interface ISmth<T> {
  id: number;
  data: T;
}

var a = [{
  id: 1,
  data: [],
}, {
  id: 2,
  data: 4,
}, {
  id: 3,
  data: "abc",
}] as const;

type ObjectIfImplemented = (typeof a extends Readonly<ISmth<any>[]> ? Object : never);
interface AssertThatReallyImplemented extends ObjectIfImplemented { }

所以我需要接口AssertThatReallyImplemented作为编译断言(如果它编译,那么一切都很好,如果不是 - 我必须修复一些东西),但我不会在任何地方使用它。

有没有更好的方法来处理错误

'AssertThatReallyImplemented' 已声明但从未使用过。

然后以某种方式导出界面

export type _BypassNoUnusedLocalsLimitation = AssertThatReallyImplemented;

标签: typescript

解决方案


给定noUnusedLocals编译器选项和非导出类型断言接口,您可以使用@ts-ignore注释来抑制'AssertThatReallyImplemented ' is declared but its value is never read错误。

为此,我们使用占位符 type 将上述“未声明”错误与实际类型断言错误分开,_否则@ts-ignore会使两者无效:

// @ts-ignore separate noUnusedLocals error from the type assertion error
type _ = AssertThatReallyImplemented
interface AssertThatReallyImplemented extends ObjectIfImplemented { } 

出于测试目的,断言类型可以像这样通用:

type AssertAssignable<T, U extends T> = true

// @ts-ignore success case
type _ = Assert
type Assert = AssertAssignable<readonly ISmth<any>[], typeof a> 

// @ts-ignore error case
type _ = AssertError
type AssertError = AssertAssignable<readonly ISmth<any>[], typeof aError> // error(OK!)

操场


推荐阅读