typescript - 如何定义类型A,其中类型A可以是除类型B之外的任何类型?

标签 typescript

作为一个具体示例,如果类型 B 是 string,则类型 A 可以是 string 以外的任何内容

我尝试过类似的方法

type A = Exclude<any, string> 

但问题是 any 并不是所有可能类型的详尽列表。类似...

const a: A = 'monkey' 

...仍然有效。但如果我做了类似的事情:

type C = string | number | boolean | Array<number>
type A = Exclude<C, string>

那么将字符串分配给 A 类型的变量将是无效的。

const a: A = 'monkey' //Invalid, as desired

问题在于将类型 C 定义为所有可能的类型实际上是不可能的。我希望可能有另一种 typescript 类型可以容纳所有可能的类型。但似乎找不到类似的东西。

最佳答案

您可以使用以下方法在函数上捍卫这一点:

type NotString<T> = Exclude<T, string>;

function noStrings<T>(anythingButAString: T & NotString<T>) {
  return anythingButAString;
}

// Works
noStrings(1);
noStrings(['okay', 'yep']);
noStrings(() => '');

// Fails
noStrings('example');

尽管您仍然可以使用 any 来解决它...但这将是非常故意的:

// You can still get around it...
noStrings<any>('example');

我想不出一种方法可以轻松地仅针对变量类型注释执行此操作。

关于typescript - 如何定义类型A,其中类型A可以是除类型B之外的任何类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50524820/

相关文章:

javascript - 如何通过异步操作维护订阅者的顺序

javascript - 为什么我在定义的数组上收到 "ERROR TypeError: Cannot read property ' length' of undefined"?

compiler-errors - Webstorm 7的TypeScript转码错误

typescript - 从@ctrl/ngx-codemirror 库,如何使用 typeScript 和 angular 5 获取 codeMirror 实例

node.js - 需要一个包含index.js的文件夹

typescript 模型添加 Mongoose 身份验证

css - Angular 2 : Set CSS class from Observable

Typescript - 在 Visual Studio Code 上找不到模块 'http'

typescript - 为什么 <array>.[n] 类型与 <array>.at(n) 不同

javascript - Ionic - 检查 Typescript 中的 ""