小编nol*_*lan的帖子

为什么我可以在打字稿中为文字对象分配未知属性?

  type ExpectedType = Array<{ name: number, gender?: string }>

  function go1(p: ExpectedType) {

  }  

  function f() {
    const a = [{name: 1, age: 2}]
    go1(a)                   // doesn't complain
    go1([{name: 1, age: 2}]) // complain 'Object literal may only specify known...'
    go1(['no matter'].map(n => ({name: 1, age: 2}))) // doesn't complain
  }
Run Code Online (Sandbox Code Playgroud)

打字稿代码如上,我的问题是最后三行不一样吗?为什么第一行可以通过,第二行投诉,第三行通过?

同样在打字稿操场上: 操场

javascript typescript reactjs angular

10
推荐指数
1
解决办法
240
查看次数

如何在打字稿中描述任何|未定义?

const localAuth = async (callback: () => any) => { 
// not sure the return type of callback, so cast a any type
  const ok = Math.random()
  if (ok > 0.5)
    return callback()
  else {
    return null
}}

localAuth(() => null).then(val => { 
  console.log(val.mayNotExist) // doesn't complain, but val maybe null!
})
Run Code Online (Sandbox Code Playgroud)

打字稿代码如上,因为回调的返回类型不确定,所以我给它分配了一个any类型,但显然any类型吞掉了'null路径',如何更改代码以不错过null的可能性?

typescript

5
推荐指数
1
解决办法
1951
查看次数

标签 统计

typescript ×2

angular ×1

javascript ×1

reactjs ×1