简体   繁体   中英

TypeScript generic method with type dependent parameter

I have an idea to have a code that automatically checks type of parameter based of generic type of the method. But the type of the parameter should be the same as type of concrete property of given generic type. Let me show you example.

let's say i have these interfaces:

interface IMessage {
    name: string,
    payload: any
}

interface IConcreteMessage {
    name: "concreteMessage",
    payload: string
}

And I'd like to call some method acception IMessage as generic parameter this way:

someobject.genericMethod<IConcreteMessage>(78)

Now the question is, how the method should be declared so the compiler throws an type error for given parameter?

public genericMethod<T extends IMessage>(payload: ??) {}

And the second thing - can I somehow extract the "concreteMessage" value within the method only from given generic parameter?

You can use a type query to achieve this:

genericMethod<T extends IMessage>(payload: T['payload']) { }

someobject.genericMethod<IConcreteMessage>(78) // will be an error

You can' get a string at runtime from a literal string type, you will need to pass a string value as a parameter.

OK so I've ended up with this solution:

genericMethod<T extends IMessage>(name: T['name'], payload: T['payload']) { }

the drawback is that I need to enter the first parameter with each call even when this property is constant but I think I can live with that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM