dcsan
dcsan

Reputation: 12305

understanding the the benefit of generics over typecasting?

I have a couple of ways to get a value from a config file, that contains various types.

I'm trying to understand the benefits of using a generic vs typecasting.

on the caller side I could do a simple cast:
const botToken = AppConfig.getenv('botToken') as string
vs
const botToken = AppConfig.getenv<string>('botToken')

On the API provider side the basic yolo any way

export class AppConfig {
    static getenv(key: configKey): any {
 ...

vs

export class AppConfig {
    static getenv<T extends any>(key: string, env?: string): T {

The question is: Does the generic method do any extra checking for example to test that given a key of X the return type is the same as the requested type in ? Or is it effectively just typecasting the results to what I asked for in in order to pass the compile checks?

Perhaps this isn't a good use case because there are so many different types and data structures this API could return... so i'm still using T extends any for the definition.

I'm also type checking the key param that is passed, given I have some knowledge of the shape of the Config env data:

export interface ConfigVars {
    prefixes?: string[];
    port?: number;
    network?: string;
    alchemyApi?: AlchemyConfig;
}
export type configKey = keyof ConfigVars

ref: https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types

Upvotes: 0

Views: 49

Answers (1)

DasKr&#252;melmonster
DasKr&#252;melmonster

Reputation: 6060

I think in your use case it will not have direct benefits.

The indirect one I can think of: You can disallow type assertions generally (e.g. via linter) and still happily use the generic version.

As this looks like a config value, it is likely impossible to have this 100% type checked at compile time.

Upvotes: 1

Related Questions