How to make package built on top of TS 4.X compatible with 3.X? Like, if you have newer version -> use new features, else -> use any
or unknown
or whatever is supported in older version.
Is there any possibility to use directives for that purpose?
You can just use an install an older version (whatever you want it to be, example: `npm i --dev typescript@3.5.2) of typescript in your npm and try to fix the errors. Then revert the typescript version to v4 or whatever it was already.
Now your code is compatible with the designated older typescript version (just make sure the functionality of your code doesn't change while updating it).
There is no way to switch between supported and unsupported features in TypeScript.
For instance, if you have a library which is built on top of TS 4.0 with variadic tuple types
there is no way to use it in a package where TS 3.0 is used.
However, you can maintain two versions of your typings: before TS4 and after TS4. For instance, take a look how lodash or react maintaince several versions of typings.
Note: TypeScript has a feature to "downlevel" the JavaScript it emits to convert language constructs from later versions of the ECMA Script standard to constructs that work in older versions. (see the compileOptions.target
field of tsconfig ).
As far as I know, TypeScript itself doesn't have such a feature to downlevel the typings files it emits (including directives at the time of this writing), but Nathan Sanders (a maintainer of Definitely Typed) maintains an open-source project, downlevel-dts
, to downlevel.d.ts files which can downlevel typings all the way down to typescript v3.4 syntax.
You will need to hook it into your build process somehow.
Here's what I think could be problematic with other proposed solutions:
"Use an older typescript version to emit your typings"
"Maintain typings for both TypeScript language version"
For any bored/keen readers who want to learn more about this general topic and good practices, semantic versioning of typescript typings is quite thoroughly discussed on semver-ts.org , which isn't a short read, but a good one.
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.