使用 any 键入交叉点

CRi*_*ice 6 inference intersection any typescript

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

超类型折叠:如果 B 是 A 的超类型,则 A & B 等价于 A。

然而:

type a = string & any; // Resolves to any, not string!?
Run Code Online (Sandbox Code Playgroud)

这个交集解析为任何。'any' 不是字符串的超类型吗?那么由于超类型折叠,这个交集不应该只是字符串吗?我错过了什么?

这里的用例是这样的:

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).
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

jca*_*alz 8

在 TypeScript 中,any是类型系统的逃生舱口。或者也许是一个黑洞,它会吞噬它接触到的所有其他类型。它被视为顶部类型(任何值都可以分配给类型的变量any)和底部类型(类型的值any可以分配给任何类型的变量)。你甚至可以说,这既是一个的超类型string 子类型string。这通常是不合理的;如果您使用any,所有类型都可以分配给所有其他类型,但这是选择退出类型系统并进行编译器会阻止的分配的有用方法。

如果您想要一个不是黑洞的真正顶级类型,请使用unknown. 你已经知道这never是真正的底部类型。有关更多有趣的阅读,请参阅Microsoft/TypeScript#9999

对于您的代码,请尝试:

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"]
}
Run Code Online (Sandbox Code Playgroud)

现在RequiredOnly["prop1"]应该表现得像你想要的那样。

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


任何帮助表示赞赏。

我看到你在那里做了什么。