Skip to content

Type recast #59503

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
kratess opened this issue Aug 1, 2024 · 2 comments
Closed

Type recast #59503

kratess opened this issue Aug 1, 2024 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@kratess
Copy link

kratess commented Aug 1, 2024

πŸ”Ž Search Terms

"recast", "type recast", "2322"

πŸ•— Version & Regression Information

Version 5.5.4

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/JYOwLgpgTgZghgYwgAgILIN4Chm+QVwGdoQ4BbCALkxzzqJPKuULClAHMBuW3AX2QAfZCHwAbMTz5YsoSLEQoAQjXrEopCtWx01jLSzacedadKwx8IBGGAB7EMkisAFAEpVeBA9bI41dABeT10CdU1mHVDdBg0magAiZzAE3l1pUxk6YBhkFzgAOliI5ECykXExDygIMHwNHjSxWuQAI2oVYLgTLx87ZoKxOw4XVrcsaWT3LiA

πŸ’» Code

interface A {
    username: {
        username: string;
    } | null;
}

interface B {
    username: {
        username: string;
    }
}

function test() {
    const a: A = {
        username: {
            username: "test"
        }
    }

    if (a.username === null) return;

    let b: B = a;
    console.log(b)
}
test();

πŸ™ Actual behavior

Type 'A' is not assignable to type 'B'.
Types of property 'username' are incompatible.
Type '{ username: string; } | null' is not assignable to type '{ username: string; }'.
Type 'null' is not assignable to type '{ username: string; }'.

πŸ™‚ Expected behavior

I know why this error message is shown up but I wonder, wouldn't it be better that the type should be recasted after the if statement? Down the lines username object cannot be null. indeed the function stops if the object is null

Additional information about the issue

No response

@nmain
Copy link

nmain commented Aug 1, 2024

Duplicate of #42384. Search terms: "parent narrowing".

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 1, 2024
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Aug 4, 2024
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants