Reputation: 408
TL;DR:
How to create typing alias in typescript the way we create dependency alias in babelrc?
The full question:
Let's say I am developing for iOS and web, and would like to write only one set of code. I am using React-Native
and something that has an interface that is very similar to React-Native
, for the sake of this question, let's call it Respond-Native
(a made-up name).
In the project, I used a component called <Picker />
. The Picker
on Respond-Native
(still the made-up library) has a property that is not present in React-Native
called onSwipe
.
But other than that, the rest of the interface is pretty much the same. Minute differences like this are all over Respond-Native
.
And to make typing easier, I have two almost identical projects. The only thing that is different is that I added an alias to the .babelrc
of the project that uses Respond-Native
:
// .babelrc
{
...
"plugins": [
...
["module-resolver", {
"root": ["./"],
"alias": {
// the alias is here
"react-native": "respond-native"
}
}]
]
}
However, when I write <Picker onChange={handleOnChange} onSwipe={handleOnSwipe} />
, the editor does not know about the dependency alias and have no idea where the prop onSwipe
comes from.
Sorry for the long build-up.
My question is, how can I do the same in creating typing alias (like I did in babelrc) so that VS Code would know which type declaration to use when checking types? (given that Respond-Native
also has a Picker
type/interface declared)
Upvotes: 1
Views: 796
Reputation: 19967
TS has the same exact mechanism like babel namely path alias:
tsconfig.json
{
"compilerOptions": {
"paths": {
// ...
}
}
}
However, due to the limitation that this config only applies to user source code rather than any node_modules
, it needs a bit of effort to "guide" TS to understand your intention.
Take for example, preact
is a lib with API highly resembles one of react
. Say you write your code using react
and later you want to switch to preact
but don't want to change your code.
./
├── node_modules/
│ ├── react/
│ └── preact/
├── typings/
│ └── react/
└── src/
└── main.ts
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["typings/*"]
}
}
}
This config is telling TS to look into typings/
folder first when resolving any modules. If there's a match, use it, else, fallback to look up node_modules/
.
With this setup, plus a soft link, we can kinda redirect the type definition of react
to point to one of preact
.
ln -s $PWD/node_modules/preact/src/index.d.ts $PWD/typings/react/index.d.ts
Upvotes: 1