Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript compile-time conditional for browser vs server code

Tags:

typescript

I'm trying to share code between browser and server parts of a web app. It might be useful to have something like an #if conditional. Is there anything like that in Typescript?

For example:

interface Card {
    id: Uuid
    text: string
    created_dt: Date
}

One the server, Uuid is a type from a database library. On the browser I'll need to use something else.

Hypothetical code:

#if compiling_for_browser
type Uuid = somelib.Uuid
#else
type Uuid = database_lib.types.Uuid
#endif

interface Card ...
like image 426
Rob N Avatar asked Apr 01 '26 16:04

Rob N


1 Answers

It appears that this is the most popular library implementing conditional compilation https://github.com/nippur72/ifdef-loader

The TypeScript team has not implemented it and doesn't seem to be moving quickly to do so, for my use (same use case, basically) I'm going to try some of the webpack conditional compilation items so I can build easily for web and react-native

like image 119
Mike Hardy Avatar answered Apr 04 '26 05:04

Mike Hardy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!