Declare an array in TypeScript

后端 未结 5 2035
不思量自难忘°
不思量自难忘° 2020-12-12 13:31

I\'m having trouble either declaring or using a boolean array in Typescript, not sure which is wrong. I get an undefined error. Am I supposed to use JavaScript

相关标签:
5条回答
  • 2020-12-12 13:49
    let arr1: boolean[] = [];
    
    console.log(arr1[1]);
    
    arr1.push(true);
    
    0 讨论(0)
  • 2020-12-12 13:51

    Here are the different ways in which you can create an array of booleans in typescript:

    let arr1: boolean[] = [];
    let arr2: boolean[] = new Array();
    let arr3: boolean[] = Array();
    
    let arr4: Array<boolean> = [];
    let arr5: Array<boolean> = new Array();
    let arr6: Array<boolean> = Array();
    
    let arr7 = [] as boolean[];
    let arr8 = new Array() as Array<boolean>;
    let arr9 = Array() as boolean[];
    
    let arr10 = <boolean[]> [];
    let arr11 = <Array<boolean>> new Array();
    let arr12 = <boolean[]> Array();
    
    let arr13 = new Array<boolean>();
    let arr14 = Array<boolean>();
    

    You can access them using the index:

    console.log(arr[5]);
    

    and you add elements using push:

    arr.push(true);
    

    When creating the array you can supply the initial values:

    let arr1: boolean[] = [true, false];
    let arr2: boolean[] = new Array(true, false);
    
    0 讨论(0)
  • 2020-12-12 13:57

    this is how you can create an array of boolean in TS and initialize it with false:

    var array: boolean[] = [false, false, false]
    

    or another approach can be:

    var array2: Array<boolean> =[false, false, false] 
    

    you can specify the type after the colon which in this case is boolean array

    0 讨论(0)
  • One way of declaring a typed array in TypeScript is

    const booleans = new Array<Boolean>();
    
    // or, if you have values to initialize 
    const booleans: Array<Boolean> = [true, false, true];
    const valFalse = booleans[1];
    
    0 讨论(0)
  • 2020-12-12 14:10

    Specific type of array in typescript

    export class RegisterFormComponent 
    {
         genders = new Array<GenderType>();   // Use any array supports different kind objects
    
         loadGenders()
         {
            this.genders.push({name: "Male",isoCode: 1});
            this.genders.push({name: "FeMale",isoCode: 2});
         }
    }
    
    type GenderType = { name: string, isoCode: number };    // Specified format
    
    0 讨论(0)
提交回复
热议问题