且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用任意类型输入相交点

更新时间:2023-11-22 22:49:34

在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.

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