Naresh
Naresh

Reputation: 25773

Typecasting in TypeScript

I have the following TypeScript code to create an ApolloClient:

return new ApolloClient({
    dataIdFromObject: (o) => o.uuid
});

The compiler is giving me the following error:

TS2339:Property 'uuid' does not exist on type 'Object'

I tried to typecast as follows:

interface DomainObject {
    uuid: string
}
...
return new ApolloClient({
    dataIdFromObject: (<DomainObject>o) => o.uuid
});

But now the compiler gets very confused and several lines around the code, which were fine before are starting to give errors. Specifically, the cast above gives this error:

TS17008:JSX element '' has no corresponding closing tag

Apparently it thinks that this is JSX code.

How can I fix this?

Thanks in advance.

Upvotes: 0

Views: 589

Answers (1)

Benjamin Hodgson
Benjamin Hodgson

Reputation: 44634

Type assertions are only valid on expressions. o here is a parameter declaration, not an expression (o => o.uuid is a lambda). But you can give a type annotation to a parameter:

return new ApolloClient({
    dataIdFromObject: (o: DomainObject) => o.uuid
});

Upvotes: 3

Related Questions