| title | Variable and Constant |
|---|---|
| order | 5 |
The variables and constants need to be declared before use.
When declared, variables must be explicitly typed or initialized (for type derivation).
When declared, constants must be initialized, and explicit type annotations are optional.
- The declaration modifier of a variables is
let, while that of constants isconst. - Constants can only be assigned when they are declared, and secondary assignments are not allowed.
Declare Boolean variables
// Explicit type
let a: boolean;
// Type derivation
let b = true;Declare integer variables
// Explicit type
let c: int;
// Type derivation
let d = 1;Declare floating-point variables
// Explicit type
let e: number;
// Type derivation
let f = 1.2;Declare string variable
// Explicit type
let g: string;
// Type derivation
let h = "content";Declare array variable
// Explicit type
let i: number[] = [];
// Type derivation
let j = [1, 2];Declare boolean constants
// Explicit type
const a: boolean = true;
// Type derivation
const b = true;Declare integer constant
// Explicit type
const c: int = 1;
// Type derivation
const d = 1;Declare floating-point constant
// Explicit type
const e: number = 1.1;
// Type derivation
const f = 1.2;Declare string constants
// Explicit type
const g: string = "hi";
// Type derivation
const h = "content";Declare array constants
// Explicit type
const i: number[] = [1.1, 2.2];
// Type derivation
const j = [1, 2];Variables are declared with no explicit type or initial value.
// error
let a;When a variable or constant is declared, the explicit type conflicts with the automatically derived type.
// error
let a: number = true;
// error
const a: string = 20;Constants are declared without initial values.
// error
const A;
// error
const B: number;Constants are assigned twice after declaration.
// error
const A = 10;
A = 20;An empty array of type is not explicitly declared.
// error
let arr1 = [];
// error
const arr2 = [];StaticScript cannot infer a type from an empty array.