Monday, November 11, 2019

Type declaration feature in TypeScript

Since ECMAScript 2015 (ECMAScript 6), javascript (typescript) begins to support class and interface, so it can share many common features as other common typed languages (C++, Java, Swift, etc), but there are still few syntax unique to typescript.

1. Property of constructor parameter
Usually, constructor parameter is just a function parameter, however, in typescript, if the constructor parameter has an accessory, like, private, public, or readonly, then it will automatically create a property for the class with the same parameter name and accessory. 
export class HttpComponent implements OnInit {
  loadedPosts = [];
  constructor(private http: HttpClient) { }


  onCreatePost(postData: Post) {
    console.log(postData);
    this.http.post('https://restapitest-d6f8c.firebaseio.com/posts.json', postData)
      .subscribe(responseData => {
        console.log(responseData);
      });
  }
}

2. interface for defining function type
Interface can be used to define a function type as below
type MyFunc = (key: number, value: string) => void;
export class HttpComponent implements OnInit {
  loadedPosts = [];
  myfunc: MyFunc;
  constructor(private http: HttpClient) {
    this.myfunc = (n: number, v: string) => {
      console.log(v + ': ' + n);
    };
   }
  onTest() {
    this.myfunc(5, 'my number is');
  }
}
3. indexable type for collection 
Interface can describe collection data type using index, which means the data collection can be indexed using the key of specified type. The name of key does not matter.
For array collection, the index is number type, and can be represented as below:
export interface Strings {
    [index: number]: string;
}
onTest() {
    const s: Strings = ['abc', 'def'];
    const s1 = s[0];
    console.log(s1);
}

For dictionary (i.e. object) collection,the index is the key type in key-value pairs as shown below.
export interface Post {
    title: string;
    content: string;
    id?: string;
}

export interface Posts {
    [id: string]: Post;
}

  onFetchPosts() {
    this.http.get('https://restapitest-d6f8c.firebaseio.com/posts.json')
      .pipe( map( (responseData: Posts) => {
        const postArray: Post[] = [];
        for (const key in responseData) {
          if (responseData.hasOwnProperty(key)) {
            postArray.push({... responseData[key], id: key});
          }
        }
        return postArray;
      })).subscribe(posts => {
        console.log(posts[0].title, posts[0].content);
      });
  }
}

The interface type definition can be used anonymously as below without explicitly defining an interface for it.
 onFetchPosts() {
    this.http.get('https://restapitest-d6f8c.firebaseio.com/posts.json')
      .pipe( map( (responseData: {[id: string]: Post}) => {
        const postArray: Post[] = [];
        for (const key in responseData) {
          if (responseData.hasOwnProperty(key)) {
            postArray.push({... responseData[key], id: key});
          }
        }
        return postArray;
      })).subscribe(posts => {
        console.log(posts[0].title, posts[0].content);
      });
  }
}
|

1 comment:

  1. Capacities are the basic structure square of any application in JavaScript. They're the manner by which you develop layers of deliberation, emulating classes, data stowing away, and modules. In TypeScript, while there are classes, namespaces, and modules, works still assume the key job in depicting how to get things done. TypeScript additionally adds some new abilities to the standard JavaScript capacities to make them simpler to work with.


    custom essay writing service

    ReplyDelete