代码之家  ›  专栏  ›  技术社区  ›  Tom

在Typescript中,如何在绑定类型安全性时提示函数?

  •  0
  • Tom  · 技术社区  · 7 年前

    考虑以下承诺:

    import { S3 } from 'aws-sdk'
    import { promisify } from 'util'
    
    const s3 = new S3({ apiVersion: '2006-03-01' })
    const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
      s3.getObject
    )
    

    这很好,只是你会有 TypeError: this.makeRequest is not a function s3.getObject this 范围。然而,这:

    const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
      s3.getObject.bind(s3)
    )
    

    破坏类型安全并将出错: Unsafe use of expression of type 'any'. (假设您使用严格模式)。

    所以我怎么能保证像s3这样的东西 getObject 在打字本里?

    1 回复  |  直到 7 年前
        1
  •  6
  •   Explosion Pills    7 年前

    您可以传递另一个调用 s3.getObject()

    const getObject = promisify<S3.GetObjectRequest, S3.GetObjectOutput>(
      name => s3.getObject(name)
    )
    

    但是,AWS SDK操作函数通常有 .promise

    s3.getObject(name).promise();