#why TypeScript is not showing error here ?

28 messages · Page 1 of 1 (latest)

craggy current
#

return 'Your request has been rejected because' + apiResponse.data

conacting string with object should be a error

winged cedar
#

!screenshot

shadow irisBOT
#
`!screenshot`:

Rather than screenshots, please provide either code formatted as:

```ts
// code here
```
Or even better, as an example on the TypeScript playground that is as simple as possible and reproduces the issue. This makes it easier to help you and increases the chances of getting an answer.

craggy current
#

interface responseType {
    data: {
        status: boolean
        reason: string
    }
}

function App() {

    const getMessage = (apiResponse:responseType) => {

        if(apiResponse.data) {
            return 'Your request has been rejected because' + apiResponse.data
        }

    }

    const response = {
        data : {
            status: true,
            reason: 'Less balance on your account !'
        }
    }

    const message = getMessage(response)


    return (
        <main>
            <input type="number" className="test-node" value="33"/>
            {message}
        </main>)
}```
#

@winged cedar sorry 🙂

winged cedar
#

it's not an error
JS let's you do that, so TS lets you do that as well

#

the object will be coerced into a string, the well known [object Object]

#

you can then concatenate the two strings

shadow irisBOT
#
const foo = "foo" + { "bar": "baz" };
console.log(foo); // prints "foo[object Object]"
craggy current
#

yea that was printed

#

ohh i thout typescript shows error in that situation as weell

#

actually i was creating a error example to show what typescript solves

#

I had to put here this ```ts if(apiResponse.data) {
return 'Your request has been rejected because' + apiResponse.reason
}

#

and shows error

winged cedar
#

yeah, I agree that is should probably show a warning, since it's an object being coerced

craggy current
#

Yea

dusk pelican
#

typescript-eslint has a rule for this

craggy current
#

you mean we can set it as enable: true then it shows error ? whats the rule ?

#

@dusk pelican and why do you think typescript lets us do it without showing error ?

dusk pelican
craggy current
#
console.log(foo); // prints "foo[object Object]"```
#

@dusk pelican

dusk pelican
#

yeah, that's kinda expected and it's typesafe

#

string + unknown = string
unknown + string = string
number + number = number
bigint + bigint = bigint
booleans might be allowed idk
but those are all the normal addition operations

#

stringifying an object has expected behavior and is typesafe, so don't see how exactly that's an issue for typescript specifically

#

typescript primarily handles type-system related stuff, after all. if you want to check for that you'd use more opinionated stuff, like the linter rule in question

craggy current
#

!close