-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Array.forEach args type error #59791
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Duplicate of #55201. |
but Expected behavior
|
Objects are not sealed. It's possible that your |
So there is a problem with item's type recognition |
How should I write best practices for the following code export interface TypeA {
name: string;
}
export interface TypeB {
name: string;
unit: string;
}
let unit: string;
const testObject: { a: TypeB[], b: TypeA[] } = {
a: [],
b: [],
};
(['a', 'b'] as const).forEach((key) => {
const ObjectValue = testObject[key]
ObjectValue.forEach((item) => {
if('unit' in item) {
unit = item.unit // error ts(2322)
}
})
}) |
export interface TypeA {
name: string;
// age: number;
}
export interface TypeB {
name: string;
unit: string;
}
type TypeTest = TypeA[] | TypeB[]
// type TypeTest = string[] | boolean[];
type Item = TypeTest extends Array<infer R> ? R : never // as type Item = TypeA
// because this?
type IsBExtendsA = TypeB extends TypeA ? 'true' : 'false' // 'true' |
No, it's working as intended. There is no defect. |
Although the logic is fine, the |
But he realistically lost the type of |
As mentioned in the other issue, it's due to subtype reduction. Look it up, there are many issues about it. It's working as intended. You can either explicitly check if interface TypeA {
name: string;
}
interface TypeB {
name: string;
unit: string;
}
let unit: string;
const testObject: { a: TypeB[], b: TypeA[] } = {
a: [],
b: [],
};
// The value is compatible with TypeA, so it can be pushed to the TypeA array.
const value = { name: 'example', unit: 12345 };
testObject.b.push(value);
(['a', 'b'] as const).forEach((key) => {
const ObjectValue = testObject[key]
ObjectValue.forEach((item) => {
if('unit' in item) {
console.log(item.unit)
unit = item.unit // error ts(2322)
}
})
}) |
🔎 Search Terms
🕗 Version & Regression Information
package.json
⏯ Playground Link
No response
💻 Code
🙁 Actual behavior
item
type OnlyTypeA
🙂 Expected behavior
item
type sould beTypeA | TypeB
Additional information about the issue
I have not idea
The text was updated successfully, but these errors were encountered: