public
- TypeScript course
- Intermediate
- Lesson 6/89
- 4 min
Learn public members with the public modifier.
What is public?
public indicates that a member is accessible from anywhere. It can be accessed from outside the class and even from other files. In TypeScript, if no modifier is written, the default is public; but writing it explicitly makes the code more readable.
class User {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const u = new User("Ada");
console.log(u.name);Default public
If you do not write any modifier, TypeScript treats the member as public by default. So name: string and public name: string have the same access; both are accessible from outside.
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}Practice User class with a public field
Define a User class with a public name: string field. Add a constructor that takes name and assigns it with this. Create a new User("Ada") and print the name field.
Starter code
// User sınıfı tanımla (herkese açık isim alanı)
// constructor ile name al
// yeni User oluştur, name'i yazdırSample solution
class User {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const u = new User("Ada");
console.log(u.name);Expected output
Ada
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the default access if no modifier is written?
- private
- protected
- static
- public Correct answer
Explanation: In TypeScript, when no modifier is written, the default is public. The member is accessible everywhere. private and protected must be written explicitly; static is not an access modifier but a class-level modifier.
2 Complete the public modifier
class User {
____ name: string;
}
class User {
public name: string;
}
Explanation: public makes a member accessible everywhere. private restricts to the class, protected to subclasses, and static moves to the class level — all different purposes.
3 public parts
| Term | Meaning |
|---|---|
public |
Accessible everywhere |
name: string (belirteç yok) |
Default public |
u.name |
External access |
public greet() |
Public method |