[英]How to check if an object type's prototype is Object.prototype in Typescript?
Given an arbitrary type, I want to check if the type is an object whose prototype is Object.prototype
.给定一个任意类型,我想检查该类型是否为 object,其原型为
Object.prototype
。 In other words, I want to exclude Functions, Sets, Maps, custom classes, etc. I can't just list every possible object type, since there's an infinite number of custom classes.换句话说,我想排除函数、集合、映射、自定义类等。我不能只列出所有可能的 object 类型,因为自定义类的数量是无限的。 Is this possible?
这可能吗?
I want to do this to recursively apply a mapping to an object. Here's what I have:我想这样做以递归地将映射应用于 object。这就是我所拥有的:
type MapDeep<T> = F<
T extends Primitive ? T
: T extends Array<infer U> ? Array<MapDeep<U>>
: T extends ReadonlyArray<infer U> ? ReadonlyArray<MapDeep<U>>
: T extends Set<infer U> ? Set<MapDeep<U>>
: T extends Map<infer K, infer V> ? Map<K, MapDeep<V>>
: T extends Partial<Record<string, any>> ? { [K in keyof T]: MapDeep<T[K]> }
: T
>;
However, for objects that have prototypes other than Object.prototype
, this doesn't work.但是,对于原型不是
Object.prototype
的对象,这不起作用。 Eg MapDeep<() => void>
returns F<{}>
instead of F<() => void>
, since it matches Partial<Record<string, any>>
.例如
MapDeep<() => void>
返回F<{}>
而不是F<() => void>
,因为它匹配Partial<Record<string, any>>
。 How can I tell if a type's prototype is Object.prototype
?我如何判断类型的原型是否为
Object.prototype
?
This is not possible.这不可能。 A typescript type does not contain information about the prototype chain of an object, it only specifies the type interface of properties and their signatures.
typescript类型不包含object的原型链信息,它只指定了属性的类型接口及其签名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.