通用参数约束为非数组 [英] Generic argument constrained to be non array

查看:37
本文介绍了通用参数约束为非数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法说方法的传递类型参数不能是数组?

is there a way to say that passed type argument of a method cannot be an array??

示例类

class A {
  public f<T /*which is not array*/>(obj: T) { /* ... */ }
}

此代码不会被编译:

const a = new A();

a.f<number[]>([42, 42]);

推荐答案

是的,有:

class A {
  public f<T>(obj: T extends Array<any> ? never : T) { /* ... */ }
}

const x = new A();
x.f(1) // ok
x.f([]) // error
x.f([1]) // error

顺便说一句,TypeScript中没有否定类型.例如,您不能这样写: not Array< any> !Array< any> ,但是TS具有条件类型.

Btw, there is no negation type in TypeScript. For instance, you can't write smth like: not Array<any> or !Array<any>, but TS has conditional types.

在我的示例中,如果参数为Array,则不会返回从不.

In my example I'm returning never if argument is Array.

这是什么意思?

这是指TS将期望一个从不类型的参数.

It is mean, that TS will expect one argument with never type.

诀窍是,您不能从字面上产生从不类型.

The trick is, that you can't produce never type literally.

您可以创建自己的否定类型:

You can create your own negation type:

type Not<T,  R> =  R extends T ? never: R;

感谢@Eldar!

这篇关于通用参数约束为非数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆