-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed as not planned
Closed as not planned
Copy link
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
π Search Terms
optional null error
π Version & Regression Information
- This is the behavior in every version I tried
β― Playground Link
π» Code
interface Author {
id: string;
}
interface Post {
id: string;
author: Author;
}
interface PostWithNull {
id: string;
author: Author | null;
}
const mixedData = [
{
id: '123',
author: null,
},
{
id: '234',
author: {
id: '1'
},
}
];
function getPostById(id: string): Post | null {
// Simulate Drizzle response type -> DO NOT CHANGE
const res = mixedData.find((record) => record.id === id) as PostWithNull;
if (!res) {
return null;
}
// The problematic part
if (res.author) {
return res; // Error: Type 'PostWithNull' is not assignable to type 'Post'.
// The code below will work.
// return {
// ...res,
// author: res.author
// }
}
return null;
}
π Actual behavior
Type 'PostWithNull' is not assignable to type 'Post'.
Types of property 'author' are incompatible.
Type 'Author | null' is not assignable to type 'Author'.
Type 'null' is not assignable to type 'Author'.
π Expected behavior
Since I validate author is not null, I expect the type Post to be correct, but instead I am getting an error that type is incorrect because it might be null
Additional information about the issue
No response
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created