如何将打字稿 T 限制为仅原始对象 [英] How to restrict the typescript T to be only primitive object

查看:29
本文介绍了如何将打字稿 T 限制为仅原始对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我问了这个问题如何限制打字稿 T 为唯一的复合对象
现在我想知道如何做相反的事情?

Yesterday I ask this question How to restrict the typescript T to be only camplex object
Now I wonder how to actually do the opposite?

class abstract MyClass<T> { }

我只想允许原始类型(字符串、布尔值等),例如:

I want only allow primitive types (string, boolean, etc) like:

class MyOtherClass extends MyClass<string> { } //<-- allowed

class MyOtherClass extends MyClass<IInterface> { } //<-- not allowed

实现这一目标的最佳方法是什么?

What is the best way to achieve that?

推荐答案

您可以创建自定义原始类型,您希望允许该类型

You can create custom primitive type, which would you like to allow

type IPrimitiveTypes = string | number | boolean;

abstract class MyClass<T extends IPrimitiveTypes> { }

游乐场

这篇关于如何将打字稿 T 限制为仅原始对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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