triston-notes/Cards/dev/Typescript Class Boilerplate.md

42 lines
1.1 KiB
Markdown
Raw Normal View History

2023-10-21 23:52:54 +00:00
---
name: Typescript Class Boilerplate
---
up:: [[Boilerplate Code]]
X:: [[TypeScript]]
tags:: #boilerplate
# Typescript Class Boilerplate
Here is an example of a simple class written in TypeScript
```tsx
class Person {
private name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public getName(): string {
return this.name;
}
public setName(name: string): void {
this.name = name;
}
public getAge(): number {
return this.age;
}
public setAge(age: number): void {
this.age = age;
}
}
```
In this example, **`Person`** is a class that has two private properties: **`name`** and **`age`**. The class has a constructor that accepts values for **`name`** and **`age`**, and assigns them to the respective properties. The class also has four methods: **`getName`**, **`setName`**, **`getAge`**, and **`setAge`**, which allow the caller to access and modify the **`name`** and **`age`** properties. The **`private`** keyword in front of the property declarations indicates that the properties can only be accessed or modified within the class itself.