Will try to infer the type automatically
// No type annotation needed -- 'myName' inferred as type 'string'
let myName = "Alice";
Specify the input of a function
// Parameter type annotation
function greet(name: string) {
console.log("Hello, " + name.toUpperCase() + "!!");
}
Less common, but you can specify return types as well
function getFavoriteNumber(): number {
return 26;
}
// The parameter's type annotation is an object type
function printCoord(pt: { x: number; y: number }) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });
//Here, we annotated the parameter with a type with two properties
// - x and y - which are both of type number. You can use , or ;
// to separate the properties, and the last separator is optional either way.
// Otherwise it would be 'any'
function printName(obj: { first: string; last?: string }) {
// ...
}
// Both OK
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
// Error
printId({ myID: 22342 });
Argument of type '{ myID: number; }' is not assignable to parameter of type 'string | number'.
If the input can be of either type you can’t just use a method that would only be applicable to a string! You have to path that shit out.
function printId(id: number | string) {
if (typeof id === "string") {
// In this branch, id is of type 'string'
console.log(id.toUpperCase());
} else {
// Here, id is of type 'number'
console.log(id);
}
}