Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

typescript如何定义一个类型为number,但是不能为200?

type Not200 = Exclude<number, 200>

发现上面这种是不行的

ps. 希望可以用在变量声明上,让let a:Not200 = 200能报错


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

1 Answer

0 votes
by (71.8m points)

可以用泛型来约束

type Not200<T> = T extends 200 ? never : number

演示使用

// 以下两种方式都可以
// declare function fn<T extends Not200<U>, U = T>(value: T): void;
declare function fn<T>(value: T & Not200<T>): void;
fn(200); // error
fn(201); // ok...

ts-playground-not200.png

TS Playground Link 中查看

参考


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...