Skip to content

Typescript error because nested value might be null even after I check it's not nullΒ #62105

@eliezra236

Description

@eliezra236

πŸ”Ž Search Terms

optional null error

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play/?target=10&pretty=false#code/JYOwLgpgTgZghgYwgAgIIFcwAsD2VkDeAUMqcsACYBcyAzmFKAOYDcRAvkUaJLIigAUc9QiTKUa9RiFZjScTLig0M2PG07dw0eEmRD6AdWDYAcugA2F0WXLU6DZm1sK1ytIrzIAPshCWLDS4EHBARAFtgAA8ICgARODA4ZABeZABtORtbcXsAcgBGACYAZjyAGiyXT3d-K0rbdgayYhzcmjzSgBYKqrJXJRpWtpyJZEK8vtImrM4AXTYiGHQQBDBgUOQmCDADMAAhAE8ASQoACjGpZgBKGj2fPwDs0hCwsGQoCFpU5EiY+MScAAdDBQOczp8QlAKNdUgA+D4QKEUIGUVIpNKUWFwb57YxmALOcQwZBnACEn1osOGbU+YHQUBAjysROmXFswBJEK+QIGeGpU0R9MZiNorJyAHoJcgACpYFAhCgoABGEAsOAA7sgNcArNq8ABrIGCqVChlMmmS6W2IG2ynNNqm6puGiU3k1E3SziNLhZOnm5mBDhEIA

πŸ’» 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

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions