TypeScript type

⒈TypeScript type

  JavaScript language data types include the following seven:

    1.boolean (Boolean), true || false

    2.null, show worthy of special keyword null, JavaScript is case-sensitive, do not mistakenly written or NULL Null

    3.undefined, attributes the variable is not defined

    4.number, it represents a number, such as 1, 1.2, etc.

    5.string, a string that represents, for example: "Hello World!"

    6.symbol, a data type (type in the newly added ES6), which represents the only example and can not be changed.

    7.object (Object), general, can be seen as an object worthy of naming container store

  JavaScript's types are processed at runtime, we can not learn to type in the code phase, so in code complexity of the situation, the lack of the type of constraint code may cause some potential pitfalls.

  Because TypeScript is a superset of JavaScript, so TypeScript support JavaScript nearly the same data type

    1.boolean type.

let areYouOk: boolean = true

    2.null

    TypeScript years, undefinedand nullboth have their own type are called undefinedand null. And  voidsimilar to their own type is not very useful:

let n: null = null;

  By default, nulland undefinedall types of sub-types. That you can  nulland undefinedassigned to numbera variable of type.

  However, when you specify a --strictNullCheckstag, nulland undefinedit can only be assigned to voidand their respective. This can avoid  many common problems. Maybe somewhere you want a pass  stringor nullor undefinedyou can use union types string | null | undefined. 

  Note: We encourage as much as possible the use of--strictNullChecks  

    3.undefined

    TypeScript years, undefinedand nullboth have their own type are called undefinedand null. And  voidsimilar to their own type is not very useful:

let u: undefined = undefined;

  By default, nulland undefinedall types of sub-types. That you can  nulland undefinedassigned to numbera variable of type.

  However, when you specify a --strictNullCheckstag, nulland undefinedit can only be assigned to voidand their respective. This can avoid  many common problems. Maybe somewhere you want a pass  stringor nullor undefinedyou can use union types string | null | undefined.

  Note: We encourage as much as possible the use of--strictNullChecks

    4.number

    And, like JavaScript, TypeScript where all numbers are floating-point numbers. These are the type of floating-point number. In addition to supporting the decimal and hexadecimal literals, TypeScript also supports binary and octal literals ES6 introduced.
let a: number = 6;
let b: number = 1_000_000;
let c: number = 0xf00d;
let d: number = 0b1010;
let e: number = 0o744;

    5.string

    And as JavaScript, TypeScript double quotation marks ( "") or single quotation marks ( '') represented by the string

let firstName: string = "fan";
let lastName: string = 'qi';  
    You can also use a template string that can define multi-line text and inline expressions. This string is backticks ( ') and is embedded in the expression of this form $ {expr}
let fullName: string = `fanqi`;
let age: number = 25;
let sentence: string = `Hello, my name is ${ fullName }.

I'll be ${ age + 1 } years old next month.`;

    Which is defined below sentencein the same manner effects:

let sentence: string = "Hello, my name is " + name + ".\n\n" +
    "I'll be " + (age + 1) + " years old next month.";

    6. The symbolvalue type by Symbolcreating constructor.

= SYM1 the let the Symbol (); 

the let SYM2 = the Symbol ( "key"); // optional string key

    7.object

  objectIt represents a non-primitive type, that is, except number, string, boolean, symbol, nullor undefinedtype outside.

let obj:object = {"name":"fanqi"};

    8. The array supports two [define]

      Ⅰ directly behind the element type plus [], thus represents an array type elements.

let list: number[] = [1, 2, 3];

      Ⅱ The second way is to use an array of generics,Array<元素类型>

let list: Array<number> = [1, 2, 3];

    9. tuple

    Tuple type allows for an element of a known type and number of the array, each element is not necessarily the same type.

    For example, a pair of values are defined  stringand numbertype tuples.

// declare tuple type 
the let X: [String, Number];
 // initialize tuple 
X = [ 'Hello', 10]; // Success 
// the Initialize IT incorrectly 
X = [10, 'Hello']; // error, the IDE will prompt species
X the let: [String, Number]; 
X = [ 'Hello', 10 ]; 
the console.log (X [ . 1] .substr (. 1));     // error, prompt, 'Number' types do not include ' substr 'method

    10. Enumeration

    enumJavaScript is a type of standard data types of supplements. Like C #, and other languages, use enumerated types can give a friendly name for a set of values.

enum Color {Red, Green, Blue}
let c: Color = Color.Green;

    By default, the 0start element number. You can also manually specify the value of the members. For example, we will change from the above example  1are numbered:

enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;

    Alternatively, all manual assignment:

enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;

  Enumerated type provides a convenient is that you can be worth by the enumeration to its name. For example, we know that the value is 2, but not sure it is mapped to the Color in which the name, we can find the appropriate name:

Color = Red. 1 {enum , Green, Blue} 
the let colorName: String = Color [2 ]; 

the console.log (colorName);   // show 'Green' because its value of the above code is 2

    11.Any

    Sometimes, we want to specify a type for those in the programming phase unclear variable of type. These values may come from dynamic content, such as input from a user or third party code libraries. In this case, we do not want the type checker to check these values, but direct them through the compilation phase checks. Then we can use the  anytype to mark these variables:

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

    When rewriting the existing code, anythe type is very useful, it allows you to optionally contain at compile-time type checking or removed. You might think  Objecthave a similar effect, as it did in other languages. But the  Objecttype of variable it just allows you to assign any value - but not be able to call any methods on it, even if it really has these methods:

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

    When you only know part of the data type, anythe type is also useful. For example, you have an array that contains different types of data:

let list: any[] = [1, true, "free"];
list[1] = 100;

    12.Void

    To some extent, voidthe type like the anytype Instead, it said there is no type. When a function does not return a value, you will usually see the return value type is  void:

function warnUser(): void {
    console.log("This is my warning message");
}

    Declare a voidvariable of type no Dayong, because you can only gives it undefinedand null:

let unusable: void = undefined;

    13.Never

  neverType indicates the type of value that will never exist. For example,  nevertype those always throws an exception or does not have a return value of the function expression or function expression arrow return type; variable may also be a  nevertype when they are never true type of protection constraint.

  neverType is a subtype of any type, may be assigned to any type; however, no type is nevera subtype or can be assigned to neverthe type (other neverthan itself). Even if  anyneither can be assigned to never.

  Here are some of the return nevertype of the function:

// return function there must never reach the end not 
function error (Message: String): {never
     the throw  new new Error (Message); 
} 

// inferred return type never 
function Fail () {
     return error ( "Something failed " ); 
} 

// return function there must never reach the endpoint can not 
function infiniteLoop (): {never
     the while ( to true ) { 
    } 
}

⒉ variable declaration

  let ES6 and const is new in the way of variable declarations. In TypeScript, let's use const and ES6 are exactly the same, we recommend the use const and let the assignment is not recommended to use var assignment.

⒊ type inference

  Even if the type of a variable is not declared, TypeScript type inference may still be made when you declare a variable according to a specified variable.

  When we assign a string and then assigned a number, the compiler will give tips.

  Whether TypeScript type inference or do we declare the variable type, being given once given the wrong value will trigger the TypeScript compiler, compile-time error that brought us the strict type checking.

= the fullName the let 'fanqi'; // the fullName AS string 
the fullName = 25; // Error, can not be assigned to the string number

⒋ type assertion

  By type inference sometimes get the right type of variable, but often we encounter another situation, you will better understand the value of this type than TypeScript, this often happens, you will know exactly the type of compiler does not infer too exact, it should be made more accurate type.

  And by the type of assertion, we can explicitly tell the compiler that we really want to do. This is an amendment scheme, in other languages, we'll use to express such a case type conversion.

  This action does not affect any play at run time, just as TypeScript declaration, as it only works at compile time. This is very much like the Word grammar checker, it is to remind and error, but does not prevent you continue to write.

  There are two types of assertions forms. One is the "angle bracket" syntax, which is the most commonly used programming language syntax:

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

  Another use as关键字:

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

  Two forms are equivalent. As for the specific use of what form it depends on personal preference. However, when you use the JSX in TypeScript, only  asthe syntax is allowed, if you must have any reason it would probably be due to the angle brackets at the JSX species has been used to express the generic.

  

 

      

  

Guess you like

Origin www.cnblogs.com/fanqisoft/p/11827665.html