使用任意类型输入相交点 [英] Type intersections using any

查看:78
本文介绍了使用任意类型输入相交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 https://github.com/Microsoft/TypeScript/pull/3622:

超级类型崩溃:A&如果B是A的超类型,则B等于A.

Supertype collapsing: A & B is equivalent to A if B is a supertype of A.

但是:

type a = string & any; // Resolves to any, not string!?

此交集解析为任意. 任何"不是字符串的超类型吗?那么由于超类型崩溃,这个交集不应该只是字符串吗?我想念什么?

This intersection resolves to any. Isn't 'any' a supertype of string? So shouldn't this intersection be just string, due to supertype collapsing? What am I missing?

这里的用例是这样的:

type PropertyMap = {
    prop1: {
        name: "somename";
        required: any;
    };
    prop2: {
        name: "someothername";
        required: never;
    }
}

type RequiredOnly = {
    [P in keyof PropertyMap]: PropertyMap[P] & PropertyMap[P]["required"]
}

// RequiredOnly["prop2"] correctly inferred to be never, but we've
// lost the type info on prop1, since it is now an any (but should
// have been narrowed to it's original type).

任何帮助表示赞赏.

推荐答案

在TypeScript中,any是来自类型系统的转义线.或者,可能是一个黑洞吞噬了它碰到的所有其他类型.它既被视为顶部类型(可以将任何值分配给any类型的变量),也可以被视为底部类型(可以将类型any的值分配给任何类型的变量).您甚至可以说它既是string 的超类型,又是string的子类型.这通常是不合理的;如果您使用any,则所有类型都可以分配给所有其他类型,但这是选择退出类型系统并进行分配的一种有用方法,编译器否则会阻止该分配.

In TypeScript, any is an escape hatch from the type system. Or maybe a black hole that eats up every other type it touches. It is treated both as a top type (any value can be assigned to a variable of type any) and a bottom type (a value of type any can be assigned to a variable of any type). You might even say it is both a supertype of string and a subtype of string. That's generally unsound; all types become assignable to all other types if you use any, but it's a useful way to opt out of the type system and make assignments that the compiler would otherwise prevent.

如果要使用不是黑洞的实心顶部类型,请使用unknown.您已经知道never是真正的底部类型.有关此内容的更有趣的阅读,请参见 Microsoft/TypeScript#9999 .

If you want a real top type which isn't a black hole, use unknown. You already know that never is the real bottom type. For more interesting reading on this, see Microsoft/TypeScript#9999.

对于您的代码,请尝试:

For your code, try:

type PropertyMap = {
    prop1: {
        name: "somename";
        required: unknown; // top type
    };
    prop2: {
        name: "someothername";
        required: never; // bottom type
    }
}

type RequiredOnly = {
    [P in keyof PropertyMap]: PropertyMap[P] & PropertyMap[P]["required"]
}

现在RequiredOnly["prop1"]的行为应像您想要的那样.

Now RequiredOnly["prop1"] should act like what you want.

希望有所帮助;祝你好运!

Hope that helps; good luck!


任何帮助表示赞赏.
Any help appreciated.

我明白你在那里做了什么.

这篇关于使用任意类型输入相交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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