TypeScript - difference between import … and import {…} (with curly braces)

后端 未结 3 1157
有刺的猬
有刺的猬 2020-12-13 12:38

Coming from Java to TS, I\'ve omitted the {...} around the imported type.

import DiscriminatorMappingData from \'./DiscriminatorMappingData\';
         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-13 13:19

    The default import needs to be without curly braces. It's easy to understand with the following example of the calculator functions.

    // Calculator.ts
    
    export default function plus() { }    // Default export 
    
    export function minus() { }           // Named export
    
    export function multiply() { }        // Named export
    

    Default Import: No Curly Braces

    // CalculatorTest.ts
    
    import plus from "./Calculator"
    

    The plus should not be enclosed with the curly braces because it is exported using the default keyword.


    Named Import: With Curly Braces

    // CalculatorTest.ts
    
    import plus, { minus, multiply } from "./Calculator"
    

    The minus and multiply should be inside the curly braces because they are exported using only the export keyword. Note that the plus is outside of the curly braces.


    Alias for Default Import

    If you want an alias for the default import, you can do it with/without curly braces:

    // CalculatorTest.ts
    
    import { default as add, minus, multiply } from "./Calculator"
    

    OR

    // CalculatorTest.ts
    
    import add, { minus, multiply} from './Calculator'
    

    Now the plus() function becomes add(). This works because only one default export is allowed per module.


    That's it! Hope that helps.

提交回复
热议问题