As the usage of the

  • As type assertion

Sometimes there are situations where you know more about a value than TypeScript does. Usually this happens when you explicitly know that an entity has a more exact type than its existing type.

Type assertions are a way of telling the editor, “Trust me, I know what I’m doing.” Type assertions are like type conversions in other languages, but without special data checking and structure. It only works at compile time. TypeScript assumes that you, the programmer, have done the necessary checks.

Type assertions come in two forms. The first is Angle bracket syntax:

let value: any = 'this is string';

let strLength: number = (<string>value).length;
Copy the code

The other is the as syntax:

let value: any = 'this is string';

let strLength: number = (value as string).length;
Copy the code

When you use JSX in TypeScript, only AS syntax assertions are allowed.

  • import * as xxx from ‘xxx’

Import * as obj from, which wraps all output into an obj object.

// index.ts
export function fn1() {
	console.log(1);
}

export function fn2() {
	console.log(2);
}


// main.ts

import * as Fn from './index.ts';

Fn.fn1();	/ / 1
Fn.fn2();	/ / 2

Copy the code
let myName = 'Joe';
let myAge = 18;
let myFn = function() {
	return 'My name is' + myName + ‘my age is’ + myAge;
}

export default {
	myName as name, / / alias
    myAge as age,
    myFn as fn,
}


import {fn, age, name} from './test.js';
import * as test from './test.js'; // Use * to batch receive, as to specify the name to receive
Copy the code
  • As ES6 provides renaming methods

Rename export and import. If you import multiple files with the same variable name, there will be a naming conflict. To solve this problem, ES6 provides a rename method, which you can do when importing names.

/*************test1.js*****************/
export let myName: string = "I'm from test1.js";

/*************test2.js*****************/
export let myName: string = "I'm from test2.js";

/*************index.js****************/
import {myName as name1} from "./test1.js";
import {myName as name2} from "./test2.js";

console.log(name1); // I'm from test1.js

console.log(name2); // I'm from test2.js
Copy the code