Orion
Orion

Reputation: 57

Declaring function argument types

I have a variable of a known type T with some members of type something | null. I have checked those members type by an if statement and then have passed them to a function .

If I set the function argument to type T I will have to setup the if statements again even though I already know that they are not null.

Only solutions I can think of is to use @ts-ignore, cast to desired type (data2.player as Player) or set the function argument type to any.

I have tried a fourth option which doesn't work for some reason.

interface Player {
    health: number;
    position: [number, number];
}

interface Data {
    level: number;
    player: Player | null;
}

function logPlayer(data2: Data & {player: Player}) {
    console.log(`Health: ${data2.player.health}`);
    console.log(`X: ${data2.player.position[0]}, Y: ${data2.player.position[1]}`);
}

function checkFunction(data: Data) {
    if (!data.player) return; // At this point data.player is definitely not null
    console.log(`You are on level ${data.level}`);
    logPlayer(data); // 'Data' is not assignable to parameter of type 'Data & { player: Player; }'
    // ...
}

Any solution or even helpful tips would be greatly appreciated.

Upvotes: 2

Views: 66

Answers (1)

Elias
Elias

Reputation: 4141

You can use this code:

function logPlayer(player: Player) {
    console.log(`Health: ${player.health}`);
    console.log(`X: ${player.position[0]}, Y: ${data2.player.position[1]}`);
}

function checkFunction(data: Data) {
    if (!data.player) return;
    console.log(`You are on level ${data.level}`);
    logPlayer(data.player);
    // ...
}

Or if you wanted to keep the logPlayer function as is, you could create a custom typeguard:

function checkFunction(data: Data) {
    if (!hasPlayer(data)) return;
    console.log(`You are on level ${data.level}`);
    logPlayer(data);
    // ...
}

function hasPlayer(data: Data): data is Data & {player: Player} {
    return Boolean(data.player);
}

Upvotes: 1

Related Questions