Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

typescript - Generic argument constrained to be non array

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

example class

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

This code would not be compiled:

const a = new A();

a.f<number[]>([42, 42]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, there is:

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

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.

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

What does it mean?

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;

Thanks @Eldar !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...