函数重载 https://www.typescriptlang.org/docs/handbook/functions.html#overloads
function prop<T, K extends keyof T>(name: K, obj: T): T[K]
function prop<K extends PropertyKey>(name: K):
<T extends Record<K, unknown>>(obj: T) => T[K]
function prop(name: any, obj?: any) {
if (obj === undefined) {
return (obj: any) => obj[name]
} else {
return obj[name]
}
}
// weak types used in impl for simplicity, as they don't matter for the caller.
// also this function body is not really complex
const valid1 = prop('foo', { foo: 'hello1' }); // string
const valid2 = prop('foo')({ foo: 'hello2' }); // string
const invalid = prop('baz')({ foo: 'hello' }); // compile error, `baz` not in { foo: string }
功能类型 https://www.typescriptlang.org/docs/handbook/interfaces.html#function-types
interface Prop {
<T, K extends keyof T>(name: K, obj: T): T[K];
<K extends PropertyKey>(name: K): <T extends Record<K, unknown>>(obj: T) => T[K]
}
const prop: Prop = (name: any, obj?: any) => {
if (obj === undefined) {
return (obj: any) => obj[name]
} else {
return obj[name]
}
}
// weak types used here for simplicity like in first solution
const valid1 = prop('foo', { foo: 'hello1' }); // string
const valid2 = prop('foo')({ foo: 'hello2' }); // string
const invalid = prop('baz')({ foo: 'hello' }); // never
console.log(valid1, valid2) // hello1 hello2
Note:函数重载和函数类型不能完全互换使用(更多信息here https://github.com/microsoft/TypeScript/issues/33482 or here https://github.com/microsoft/TypeScript/issues/35338#issuecomment-558867975)。对于后者,可能需要用以下方式注释类型any
在函数实现部分中考虑定义的调用签名中不兼容的返回类型 - 检查此举个例子。