李恒道 发表于 2022-8-1 15:18:05

typescript Equal函数相等性推测

```
type Equal<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <
T
>() => T extends Y ? 1 : 2
? A
: B;
```
这里的
```
<T>() => T extends X ? 1 : 2) extends <
T
>() => T extends Y ? 1 : 2
```
实际只是一个辅助作用
并没有参与实际推断
具体可以参考
https://github.com/Microsoft/TypeScript/issues/27024
```
@jituanlin AFAIK it relies on conditional types being deferred when T is not known. Assignability of deferred conditional types relies on an internal isTypeIdenticalTo check, which is only true for two conditional types if:

Both conditional types have the same constraint
The true and false branches of both conditions are the same type
```
当函数T是未知时,依赖于延迟推断类型,延迟推断类型的可分配性依赖于内部isTypeIdenticalTo的检查,仅在两种情况下为真,
1.extends分支结果是相同类型,
2.两个条件类型是同一类型,

```
<T>() => T extends X ? 1 : 2 和 <T>() => T extends X
```
时返回true,通过该方法判断类型是否是readonly

```
export type MutableKeys<T extends object> = {
-?: Equal<
    { : T },
    { -readonly : T },
    P,
    never
>;
};

expectType<MutableKeys<{ a: string; readonly b: string }>>('a');
```
但更具体的理论就不清楚了....
页: [1]
查看完整版本: typescript Equal函数相等性推测