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

时间:2018-05-25 08:29:53

标签: 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定义为所有可能的类型实际上是不可能的。我希望可能会有另一种包含所有可能类型的打字稿类型。但似乎无法找到类似的东西。

1 个答案:

答案 0 :(得分:1)

您可以使用以下功能对此功能进行辩护:

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');

我想不出一种只为变量类型注释轻松做到这一点的方法。

相关问题