2021年6月24日 星期四

[typescript] Object Type: Create a new type, use it and print out

Object Type: Create new type, use it and print out

井民全, Jing, mqjing@gmail.com


Object type is useful to descript complex data type such as status, configure, member, etc. As doc[1] said, we group and pass around data is through objects. Here is a usage example. For more great docs, check[1-2].


Keyword

interface -- create a new type

type -- a type alias


Code

// Declare a new object type Status

interface Status  {

    num: number;

}


// Define a variable status that is Status type with initial value

let status:Status = {num: 0};


// Update 

status.num++;


// Debug and print out

console.log('/increase. status = ' + JSON.stringify(status));




# Declare  a new object type Person

interface Person {

  name: string;

  age: number;

}


# usage

function greet(person: Person) {

  return "Hello " + person.name;

}



References

  1. Object Types, https://www.typescriptlang.org/docs/handbook/2/objects.html

  2. Types vs. interfaces in TypeScript, https://blog.logrocket.com/types-vs-interfaces-in-typescript/