[英]How to express idempotent (self flatten) types in TypeScript?
There are types with self flattening nature that is called Idempotence:有一些具有自展平性质的类型,称为幂等:
https://en.wikipedia.org/wiki/Idempotence https://en.wikipedia.org/wiki/Idempotence
Idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.
幂等性是数学和计算机科学中某些运算的属性,它们可以多次应用而不会改变初始应用后的结果。
In JavaScript/TypeScript, we have Object/Number object for instance of idempotence.在 JavaScript/TypeScript 中,我们有Object/Number 对象作为幂等的实例。
A real world use-case is to write your own Promises with proper type in TypeScript.一个真实世界的用例是在 TypeScript 中使用正确的类型编写自己的 Promise。 You can never have
Promise<Promise<T>>
only ever Promise<T>
since promises auto-flatten.你永远不可能有
Promise<Promise<T>>
只有Promise<T>
因为承诺会自动展平。 The same can happen with monads, for example.例如,monad 也会发生同样的情况。
console.log( Number(5) === Number(Number(5)) ); // true
In a concise way, it's often expressed like以简洁的方式,它通常表示为
TTX = TX TTX = TX
I somehow managed to write in function我以某种方式设法写在函数中
const toObject = <A, X>(x: A): A extends T<X> ? A : //...
((X:object)=> {/* ... */})(Object(x)) ;
A extends T<X> ? A : //...
A extends T<X> ? A : //...
works in the context of inside of some functions, but I don't know how to write the type itself alone, and even with function structure, it's very complicated, and I feel something is very wrong. A extends T<X> ? A : //...
在一些函数内部的上下文中起作用,但是我不知道如何单独编写类型本身,即使是函数结构,它也很复杂,我觉得有些地方很不对劲。
What I want to know and write is a definition of the idempotent type in TypeScript我想知道和写的是TypeScript中幂等类型的定义
type T<X> = ???
//where
T<T<X>> === T<X>
You could write an idempotent wrapper around some inner type:你可以围绕一些内部类型编写一个幂等的包装器:
// just for reference, more practically this could be Promise<T>
type InnerType<T> = [T];
type IdempotentWrapper<X> = X extends InnerType<unknown> ? X : InnerType<X>;
type Foo = IdempotentWrapper<number>; // equivalent to InnerType<number>
type Bar = IdempotentWrapper<IdempotentWrapper<number>>; // equivalent to InnerType<number> as well
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.