linbudu599 / TS-AMA

Show me your typescript playground link.
MIT License
20 stars 1 forks source link

Why not intersection `T` #1

Open NWYLZW opened 5 months ago

NWYLZW commented 5 months ago
function foo<T extends object>(t: T | undefined) {
  return { ...t, foo: 1 }
}
const t0 = foo({ a: 1 })
//    ^? t0 = { foo: number }

ts play

linbudu599 commented 5 months ago

因为 t 的类型包括了 undefined,TS 觉得不能保证这个泛型类型必定存在,所以在展开操作里去掉了,去掉 undefined 类型就会是 a & foo 了

NWYLZW commented 5 months ago

因为 t 的类型包括了 undefined,TS 觉得不能保证这个泛型类型必定存在,所以在展开操作里去掉了,去掉 undefined 类型就会是 a & foo 了

感觉得 { foo: number } | ({ foo: number } & T) ,但是看着又觉得安全性没办法保证,不过你说的应该是对的,只要把 snc(strictNullCheck) 给关了就能推断出来了