Issue
Say I have a package that exports a User type:
export const User: {
name: string;
};
And I want to use the name property aliased as username in my code. In normal JavaScript I'm able to do something like this:
const { User: { name: username } } = require('user.js');
/* do something with `username` ... */
I want to convert the file I'm working with into TypeScript and so I'll use ES6 module imports. How can I achieve the same as above using import instead of require?
Solution
You can't destructure objects in static import statements, but you can rename them using the as keyword:
import {User as USER} from './user.js';
If you are okay with using a dynamic import, you can destructure:
const {User: {name: username}} = await import('./user.js');
There are pros and cons to both static and dynamic importing methods which you can read about in the links I shared.
Answered By - jsejcksn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.