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)
打字稿代码如上,我的问题是最后三行不一样吗?为什么第一行可以通过,第二行投诉,第三行通过?
同样在打字稿操场上: 操场
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的可能性?