TypeScript
Last updated
Last updated
Scope: by default members in a class are public
Enum: an enum is a way of giving more friendly names to sets of numeric values
String enum: use custom Type. See more here.
Do we put return type when defining function?
Yes. getSum(a: number, b: number): number {}
Type assertion: (<string>someValue).length;
We have static
, readonly
const
is for variable. No one can modify it after assigned.
readonly
is for property (class property to property in interface). Properties must be initialized
Function overload, this is possible in TypeScript but it's not supported by JavaScript.
Default parameter: getSum(data: number[], skipNegative: boolean = false)
var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4; // error
public label(row: {0: string, 1: number}): string {
var t:[number, string] = [1, "message"]
// pick only the data we need using destructing
// Function signature: getAccountInfo(): {balance: number; cardStatus: string; cardNumber: string; cardHolder: string}
// before:
.then((response:any) => {
const data = this.getAccountInfo()
return {
balance: data.balance,
cardStatus: data.cardStatus
};
// after
.then((response:any) => {
const {balance, cardStatus} = this.getAccountInfo()
return {
balance,
cardStatus
};
If the data is NOT used anywhere, don't put private.
constructor(private data?: any) {
this.model = this.extract(data);
}
static
must be class member.