// the type-checker checks the call to printLabel and ensures there is a field
// property of type string
function printLabel(labelledObj: {label: string }) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
// USING AN INTERFACE
interface LabelledValue {
label: string;
}
function printLabel (labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
// not all properties of an interface may be required
// interfaces with optional properties are written similar to other interfaces,
// with each optional property denoted by a ? at the end of the property name
// in the declaration
interface squareConfig {
height: number;
width: number;
color?: string;
}
// some properties should only be modifiable when an object is first created
// you can specify this by putting 'readonly' before the name of the property
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
// typescript comes with a ReadonlyArray<T> type that is the same as Array<T>,
// with all mutating methods removed
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
// in addition to describing the wide range of shapes that JavaScript objects
// can take, interfaces can also describe function types
// to describe a function type with an interface, we give the interface a
// call signature - similar to a function declaration
interface SearchFunc {
(source: string, subString: string): boolean; // call signature
// only the parameter list and return type given
// each parameter in the list requires both a name and type
}
// once defined, the interface can be used like we would use other interfaces
// review
// we can also describe types that we can 'index into' like a[10] or ageMap["daniel"]
// indexable types have an index signature that describes the types we can
// use to index into the object, along with the corresponding return types
// when indexing
interface StringArray {
[index: number]: string; // index signature
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
// the index signature states that when a StringArray is indexed with a number,
// it will return a string