TypeScript
TypeScript copied to clipboard
The type reduction of the in operator is invalid in ts 5.5
🔎 Search Terms
The type reduction of the in operator is invalid in ts 5.5
🕗 Version & Regression Information
ts 5.5
⏯ Playground Link
No response
💻 Code
export type IZhgztDeptTreeChildren = {
organizationCode: string
deptId: string
name: string
sort: number
parentId: string
divisionCode: string
deptType: string
children: IZhgztDeptTreeChildren[]
id: string
}
type userInfo = { name: string; userId: string; id: string; isLeaf: boolean }
const handleNodeClick = (data: IZhgztDeptTreeChildren | userInfo) => {
if ('userId' in data) {
data = handleFullPeopleName(JSON.parse(JSON.stringify(data)) as userInfo) as userInfo
}
console.log(data)
}
function handleFullPeopleName(data: userInfo): userInfo {
return data
}
🙁 Actual behavior
data Type inference (parameter) data: IZhgztDeptTreeChildren | userInfo ,but i expect only userInfo 。is bug?how to solve this problem
🙂 Expected behavior
expect only userInfo
Additional information about the issue
data Type inference (parameter) data: IZhgztDeptTreeChildren | userInfo ,but i expect only userInfo 。is bug?how to solve this problem
This seems to be just a quickinfo confusion, the expected narrowed type is seen on subsequent lines: playground
Do you have any examples where consuming data fails to have the right types?
Duplicate of https://github.com/microsoft/TypeScript/issues/52547
Duplicate of #52547
I replied to that one too and didn't even remember it 🤦
Duplicate of #52547
I replied to that one too and didn't even remember it 🤦
in my example ,Subsequent uses of value will type incorrectly: for example:
type userInfo = { name: string; userId: number; id: string }
type IZhgztDeptTreeChildren = {
children: IZhgztDeptTreeChildren[]
id: string
}
let selectedUserInfoArr = [
{
userId: 1,
},
]
const handleNodeClick = (data: IZhgztDeptTreeChildren | userInfo) => {
if ('userId' in data) {
let index = selectedUserInfoArr.findIndex((item) => {
return item.userId === data.userId
})
if (index == -1) {
data = handleFullPeopleName(JSON.parse(JSON.stringify(data)))
}
}
}
function handleFullPeopleName(data: userInfo): userInfo {
return data
}
how to solve this problem?
@codeflyA That's #9998, because TS doesn't know when the callback passed to findIndex will be invoked.
@codeflyA That's #9998, because TS doesn't know when the callback passed to
findIndexwill be invoked.
i read you answer,but if i delete code
// if (index == -1) {
// data = handleFullPeopleName(JSON.parse(JSON.stringify(data)))
// }
the ts error disappear
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.