functionlogName(something: { name:string }) {console.log(something.name);}var person = { name:'matt', job:'being awesome' };var animal = { name:'cow', diet:'vegan, but has milk of own species' };var random = { note:`I don't have a name property` };logName(person); // okaylogName(animal); // okaylogName(random); // Error: property `name` is missing
functionlogIfHasName(something: { name?:string }) {if (something.name) {console.log(something.name); }}var person = { name:'matt', job:'being awesome' };var animal = { name:'cow', diet:'vegan, but has milk of own species' };logIfHasName(person); // okaylogIfHasName(animal); // okaylogIfHasName({neme: 'I just misspelled name to neme'}); // Error: object literals must only specify known properties. `neme` is excessive here.
// AssuminginterfaceState { foo:string; bar:string;}// You want to do: this.setState({foo:"Hello"}); // Error: missing property bar// But because state contains both `foo` and `bar` TypeScript would force you to do: this.setState({foo:"Hello", bar:this.state.bar}};
// AssuminginterfaceState { foo?:string; bar?:string;}// You want to do: this.setState({foo:"Hello"}); // Yay works fine!// Because of freshness it's protected against typos as well!this.setState({foos:"Hello"}}; // Error: Objects may only specify known properties// And still type checkedthis.setState({foo:123}}; // Error: Cannot assign number to a string