我想声明一个函数,它可以获取一个对象加上一个嵌套属性键数组,并导出嵌套值的类型作为函数的返回类型.
例如
const value = byPath({ state: State, path: ['one', 'two', 'three'] });
// return type == State['one']['two']['three']
const value2 = byPath({ state: State, path: ['one', 'two'] });
// return type == State['one']['two']
Run Code Online (Sandbox Code Playgroud)
我能够组合起来的最好的是以下内容,但它比我想要的更加冗长,并且我必须为每个嵌套级别添加一个函数重载.
export function byPath<
K1 extends string,
R
>({ state, path }: {
state: {[P1 in K1]?: R},
path: [K1]
}): R;
export function byPath<
K1 extends string,
K2 extends string,
R
>({ state, path }: {
state: {[P1 in K1]?: {[P2 in K2]?: R}},
path: [K1, …Run Code Online (Sandbox Code Playgroud) 这是普通 ol' js 中的管道函数:
const pipe = (f, ...fs) => x =>
f === undefined ? x : pipe(...fs)(f(x))
const foo = pipe(
x => x + 1,
x => `hey look ${x * 2} a string!`,
x => x.substr(0, x.length) + Array(5).join(x.substring(x.length - 1)),
console.log
)
foo(3) // hey look 8 a string!!!!!Run Code Online (Sandbox Code Playgroud)
我如何用类型在打字稿中写同样的东西?
即当我在管道函数时,我可以从当前最后一个函数的返回类型中获取类型信息
如果一个函数有一组函数,其中一个函数的输出是下一个函数的输入,即每对的输入和输出类型必须对齐,但不同对之间可能不同。如何使 Typescript 编译器能够理解类型:
type A = () => string
type B = (str: string)=> number
type C = (num: number)=> [number,number]
const a:A = ()=>'1'
const b:B = (str)=>parseInt(str)
const c:C = (num)=>[num,num]
//typescript is fine with this
console.log(`result: ${c(b(a()))}`)
//but not what follows, even though it's similar functionality
//this is not dynamic typing as the order in which functions
//are dealt with is known and fixed at compile time
const arrayOfFunctions: [A,B,C] = [a,b,c]
let prevResult: any
arrayOfFunctions.forEach(fn=>{
// …Run Code Online (Sandbox Code Playgroud) typescript ×3