Jørgen Tvedt
Jørgen Tvedt

Reputation: 1284

Typescript - Get type of property, compile time

I sometimes just like to copy the type of a property, instead of using the property's type directly. This might be because the type is declared inline, or because I expect it to change. The property is on an interface that's part of a namespace.

I have tried:

type IIdentity = Contracts.ICustomer.identities[number]

But that claims ICustomer is not a member of the Contracts namespace, which is somewhat misleading.

I have also tried a number of typeof combinations, all without results.

The only way I have come up with that works, is through a dummy function and the excellent new ReturnValue function, but this seems overly complex:

const evilDummy = (x: Contracts.ICustomer) => x.identities[0]
type IIdentity = ReturnType<typeof evilDummy>

Anyone got a better way?

Upvotes: 2

Views: 623

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250226

You can use type queries:

interface ICustomer{ identities: boolean[] }
type IIdentity = ICustomer['identities'][number] // will be boolean

Edit

Or if the interface is in a namespace

namespace Contracts {
    export interface ICustomer{ identities: boolean[] }
}
type IIdentity = Contracts.ICustomer['identities'][number] // will be boolean

Upvotes: 2

Related Questions