我希望TS的最新版本(参见示例#43183)能够在不使用不安全铸造的情况下实现这种模式.有什么 idea 吗?(playground)
export type Mapping = {
number: number;
string: string;
};
function get<K extends keyof Mapping>(key: K): Mapping[K] {
switch (key) {
case "number":
// ERROR: Type 'number' is not assignable to type 'Mapping[K]'
return 42; // Adding "as Mapping[K]" works, but that's not type-safe
case "string":
// ERROR: Type 'string' is not assignable to type 'Mapping[K]'
return "hello";
default:
throw "Never reached, but otherwise TS throws: Function lacks...";
}
}
const usageWorksAsExpected = { n: get("number"), s: get("string") };