相关疑难解决方法(0)

TypeScript:使用数组获取深层嵌套的属性值

我想声明一个函数,它可以获取一个对象加上一个嵌套属性键数组,并导出嵌套值的类型作为函数的返回类型.

例如

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)

typescript

8
推荐指数
1
解决办法
905
查看次数

如何在打字稿中键入管道函数?

这是普通 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

6
推荐指数
1
解决办法
1359
查看次数

打字稿中的链接函数类型

如果一个函数有一组函数,其中一个函数的输出是下一个函数的输入,即每对的输入和输出类型必须对齐,但不同对之间可能不同。如何使 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
推荐指数
1
解决办法
1707
查看次数

标签 统计

typescript ×3