//// type with optional readonly property.// baz?:string is the same as baz:string|undefined//type Foo = {readonly bar: string;readonly baz?: string;}const foo:Foo = {bar: "bar"}console.log(foo.bar) // prints 'bar'console.log(foo.baz) // prints undefined
//// interface with optional readonly property//interface iFoo {readonly bar: string;readonly baz?: string;}
const ifoo:iFoo = {bar: "bar"}console.log(ifoo.bar) // prints 'bar'console.log(ifoo.baz) // prints undefined
//// class implements bar as a getter,// but leaves off baz.//class iBarClass implements iFoo {
get bar() { return "bar" }}const iBarInstance = new iBarClass()console.log(iBarInstance.bar) // prints 'bar'console.log(iBarInstance.baz) // prints 'undefined'// accessing baz gives warning that baz does not exist// on iBarClass but returns undefined// note that you could define baz as a getter// and just return undefined to remove the warning.
//// class implements optional readonly property as a getter//class iBazClass extends iBarClass {private readonly _baz?: string
constructor(baz?:string) {super()this._baz = baz}
get baz() { return this._baz; }}
const iBazInstance = new iBazClass("baz")console.log(iBazInstance.bar) // prints barconsole.log(iBazInstance.baz) // prints baz
class Name{private _name: string;
getMethod(): string{return this._name;}
setMethod(value: string){this._name = value}
get getMethod1(): string{return this._name;}
set setMethod1(value: string){this._name = value}}
class HelloWorld {
public static main(){
let test = new Name();
test.setMethod('test.getMethod() --- need ()');console.log(test.getMethod());
test.setMethod1 = 'test.getMethod1 --- no need (), and used = for set ';console.log(test.getMethod1);}}HelloWorld.main();
class Car {private tiresCount = 4;get yourCarTiresCount(){return this.tiresCount;}set yourCarTiresCount(count) {alert('You shouldn\'t change car tire count')}}
上面的代码执行以下操作:
get和set为yourCarTiresCount(不是为了#3)创建getter和setter。
getter是:
function () {return this.tiresCount;}
而setter是:
function (count) {alert('You shouldn\'t change car tire count');}
// dataStore.tsexport const myData: string = undefined; // just for typing supportlet _myData: string; // for memoizing the getter results
Object.defineProperty(this, "myData", {get: (): string => {if (_myData === undefined) {_myData = "my data"; // pretend this took a long time}
return _myData;},});
然后,在另一个文件中,您有:
import * as dataStore from "./dataStore"console.log(dataStore.myData); // "my data"
class Person {constructor(name: string) {this._name = name;}
private _name: string;
get name() {return this._name;}
// first checks the length of the name and then updates the name.set name(name: string) {if (name.length > 10) {throw new Error("Name has a max length of 10");}
this._name = name;}
doStuff () {this._name = 'foofooooooofoooo';}
}
const person = new Person('Willem');
// doesn't throw error, setter function not called within the object method when this._name is changedperson.doStuff();
// throws error because setter is called and name is longer than 10 charactersperson.name = 'barbarbarbarbarbar';
export class Attributes<T> {constructor(private data: T) {}get = <K extends keyof T>(key: K): T[K] => {return this.data[key];};set = (update: T): void => {// this is like spread operator. it will take this.data obj and will overwrite with the update obj// ins tsconfig.json change target to Es6 to be able to use Object.assign()Object.assign(this.data, update);};getAll(): T {return this.data;}}
class Person {private _age: number;private _firstName: string;private _lastName: string;
public get age() {return this._age;}
public set age(theAge: number) {if (theAge <= 0 || theAge >= 200) {throw new Error('The age is invalid');}this._age = theAge;}
public getFullName(): string {return `${this._firstName} ${this._lastName}`;}}
class UserAccount {name: string;accountType = "user";
email: string;//Property 'email' has no initializer and is not definitely assigned in the constructor.address: string | undefined;
constructor(name: string) {this.name = name;// Note that this.email is not set}}