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

type Not200 = Exclude<number, 200>

发现上面这种是不行的

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

阅读 1.7k
1 个回答

可以用泛型来约束

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 中查看

参考

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进