TypeScript - Variables

Typescript variable declaration

It’s surprising how complex this is for a newbie.

Check out this code

1
2
public onRowClicked(company: Company) {
console.log("row clicked: ", company);

company:Company – left side is variable name, right side is variable type. So we have declared a variable named company which has a data type of Company.

Here is a declaration and an assignment

1
2
3
4
5
6
openModalWithComponent() {
const initialState = {
list: [
{"tag":'Count',"value":this.itemList.length}
]
};

In this case list is the variable name, right side is a list of name-value’s. In this case 2 items. The first has a name of Tag which is given a value of ‘Count’, the second is named value, and this has a value of the number of elements in the itemList variable

When you start declaring variable types, it will sometimes start you on a path that you don’t expect. For example the following line:

1
var path = $('#TextBox_Path').val();

It would seem an obvious thing to do with this line would be to turn it into a string.

1
var path: string = $('#TextBox_Path').val();

But this gives you a message something like: Argument of type ‘string | number | string[]’ is not assignable to parameter of type ‘string’. The reason is because val returns
an array of characters. to fix that you could cast this as a string

1
var path: string = ($('#TextBox_Path').val() as string);

Typescript supports the following data types

  • boolean
  • number
  • string
  • array
  • tuple
  • Enum
  • Unknown
  • Any
  • Void
  • Null and undefined
  • Never
  • Object

Object Notes

Here is how to print out an object’s contents.

1
console.log(`result - ${JSON.stringify(result)}`);

String Notes

1
console.log(`isActive= ${this.policyTypeCodeForm.controls.isActive.value}`);

String delimiters
• ‘ – the single quote
• “ – the double quote
• ` - the backtick – useful when you want to compose a string of string parts and variable parts. In the example above we’re passing a screen control value into the string.

References