ID: Indonesia
Original Text:
TypeScript - Typeof Type Operator
Hello there, future coding wizards! Today, we're going to embark on an exciting journey into the world of TypeScript, specifically focusing on the typeof
type operator. Don't worry if you're new to programming; I'll be your friendly guide, and we'll explore this topic step by step. So, grab a cup of your favorite beverage, and let's dive in!
What is the typeof Type Operator?
Before we get into the nitty-gritty, let's understand what the typeof
type operator is all about. In TypeScript, typeof
is a powerful tool that allows us to extract the type of a variable or expression. It's like a magical magnifying glass that lets us peek into the type information of our code.
Why is it useful?
Imagine you're a detective trying to solve a mystery. The typeof
operator is like your trusty magnifying glass, helping you uncover clues about the types in your code. This can be incredibly helpful when you're working with complex data structures or when you want to create more flexible and reusable code.
Syntax
The syntax of the typeof
type operator is straightforward. Here's how it looks:
typeof variableOrExpression
It's that simple! You just put typeof
in front of the variable or expression you want to examine, and voilà! TypeScript will give you the type information.
Examples
Now, let's roll up our sleeves and look at some practical examples. I'll show you various scenarios where the typeof
type operator can be super useful.
Example 1: Basic Usage
Let's start with a simple example:
let myNumber = 42;
type MyNumberType = typeof myNumber;
// Usage
let anotherNumber: MyNumberType = 100; // This is valid
let myString: MyNumberType = "Hello"; // Error: Type 'string' is not assignable to type 'number'
In this example, we're using typeof myNumber
to create a new type MyNumberType
. TypeScript infers that myNumber
is of type number
, so MyNumberType
becomes equivalent to the number
type.
Example 2: Working with Objects
The typeof
operator really shines when working with objects. Let's take a look:
const user = {
name: "Alice",
age: 30,
isAdmin: false
};
type User = typeof user;
// Usage
const newUser: User = {
name: "Bob",
age: 25,
isAdmin: true
};
const invalidUser: User = {
name: "Charlie",
age: "Twenty" // Error: Type 'string' is not assignable to type 'number'
};
Here, we're using typeof user
to create a User
type that matches the structure of our user
object. This is incredibly useful when you want to ensure that other objects have the same shape.
Example 3: Function Types
The typeof
operator can also be used with functions. Check this out:
function greet(name: string): string {
return `Hello, ${name}!`;
}
type GreetFunction = typeof greet;
// Usage
const sayHi: GreetFunction = (name: string) => `Hi, ${name}!`;
const invalidGreet: GreetFunction = (name: number) => `Hello, ${name}`; // Error: Parameter 'name' is not assignable
In this example, we're using typeof greet
to create a GreetFunction
type that matches the signature of our greet
function. This ensures that any function assigned to a variable of type GreetFunction
has the same parameter and return types.
Example 4: Enum Types
typeof
can be particularly handy when working with enums:
enum Color {
Red,
Green,
Blue
}
type ColorType = typeof Color;
// Usage
const colorUtils: ColorType = {
Red: 0,
Green: 1,
Blue: 2
};
const invalidColorUtils: ColorType = {
Red: 0,
Green: 1,
Yellow: 2 // Error: 'Yellow' does not exist in type 'typeof Color'
};
Here, typeof Color
gives us a type that represents the structure of the Color
enum. This can be useful for creating objects that need to mirror the structure of an enum.
Example 5: Combining with keyof
The typeof
operator plays well with other TypeScript features. Let's see how it works with keyof
:
const dimensions = {
width: 100,
height: 200
};
type DimensionKeys = keyof typeof dimensions;
// Usage
function getDimension(key: DimensionKeys): number {
return dimensions[key];
}
console.log(getDimension("width")); // Valid
console.log(getDimension("depth")); // Error: Argument of type '"depth"' is not assignable to parameter of type 'keyof typeof dimensions'
In this example, we're combining keyof
and typeof
to create a type that represents the keys of our dimensions
object. This allows us to create functions that can only accept valid keys of the object.
Methods Table
Here's a table summarizing the key points about the typeof
type operator:
Method | Description | Example |
---|---|---|
typeof variable |
Extracts the type of a variable | type T = typeof myVariable; |
typeof object |
Creates a type matching the structure of an object | type ObjectType = typeof myObject; |
typeof function |
Creates a type matching the signature of a function | type FuncType = typeof myFunction; |
typeof enum |
Creates a type representing the structure of an enum | type EnumType = typeof MyEnum; |
keyof typeof object |
Creates a union type of an object's keys | type Keys = keyof typeof myObject; |
Conclusion
And there you have it, folks! We've explored the typeof
type operator in TypeScript, from its basic syntax to more advanced use cases. Remember, typeof
is like a Swiss Army knife in your TypeScript toolkit – it's versatile, powerful, and can make your code more robust and flexible.
As you continue your TypeScript journey, you'll find more and more situations where typeof
can come in handy. It's all about practice and exploration. So, don't be afraid to experiment and see what you can create with this powerful tool.
Happy coding, and may your types always be strong and your errors few!
Terjemahan:
TypeScript - Operator Typeof
Halo sana, para ahli pemrograman masa depan! Hari ini, kita akan mengemban perjalanan menarik ke dunia TypeScript, khususnya fokus pada operator typeof
. Jangan khawatir jika Anda baru dalam pemrograman; saya akan menjadi panduan ramah Anda, dan kita akan mengexploreasi topik ini langkah demi langkah. Jadi, ambil secangkir minuman kesukaan Anda, dan mari kita masuk ke dalamnya!
Apa Itu Operator typeof?
Sebelum kita masuk ke hal yang berat, mari kita mengerti apa itu operator typeof
. Dalam TypeScript, typeof
adalah alat yang kuat yang memungkinkan kita untuk mengekstrak tipe dari variabel atau ekspresi. Itu seperti kaca pembesar magis yang memungkinkan kita untuk melihat informasi tipe kode kita.
Mengapa itu berguna?
Bayangkan Anda adalah detektif yang mencoba untuk memecahkan misteri. Operator typeof
adalah seperti kaca pembesar tepercaya Anda, membantu Anda untuk menemukan petunjuk tentang tipe di kode Anda. Ini bisa sangat membantu saat Anda bekerja dengan struktur data kompleks atau saat Anda ingin membuat kode yang lebih fleksibel dan dapat dipakai kembali.
Sintaks
Sintaks operator typeof
adalah mudah. Berikut adalah penampilannya:
typeof variableOrExpression
Itu saja! Anda hanya perlu menempatkan typeof
di depan variabel atau ekspresi yang Anda ingin tinjau, dan voilà! TypeScript akan memberikan Anda informasi tipe.
Contoh
Sekarang, mari kita melebur lengan dan lihat beberapa contoh praktis. Saya akan menunjukkan Anda berbagai konteks di mana operator typeof
bisa sangat berguna.
Contoh 1: Penggunaan Dasar
Mari kita mulai dengan contoh sederhana:
let myNumber = 42;
type MyNumberType = typeof myNumber;
// Penggunaan
let anotherNumber: MyNumberType = 100; // Ini valid
let myString: MyNumberType = "Hello"; // Kesalahan: Tipe 'string' tidak dapat diassign ke tipe 'number'
Dalam contoh ini, kita menggunakan typeof myNumber
untuk membuat tipe baru MyNumberType
. TypeScript menyimpulkan bahwa myNumber
adalah tipe number
, sehingga MyNumberType
menjadi setara dengan tipe number
.
Contoh 2: Bekerja dengan Objek
Operator typeof
benar-benar menonjol saat bekerja dengan objek. Mari kita lihat:
const user = {
name: "Alice",
age: 30,
isAdmin: false
};
type User = typeof user;
// Penggunaan
const newUser: User = {
name: "Bob",
age: 25,
isAdmin: true
};
const invalidUser: User = {
name: "Charlie",
age: "Twenty" // Kesalahan: Tipe 'string' tidak dapat diassign ke tipe 'number'
};
Di sini, kita menggunakan typeof user
untuk membuat tipe User
yang cocok dengan struktur objek user
kita. Ini sangat berguna saat Anda ingin memastikan bahwa objek lain memiliki bentuk yang sama.
Contoh 3: Tipe Fungsi
Operator typeof
juga dapat digunakan dengan fungsi. Lihat ini:
function greet(name: string): string {
return `Hello, ${name}!`;
}
type GreetFunction = typeof greet;
// Penggunaan
const sayHi: GreetFunction = (name: string) => `Hi, ${name}!`;
const invalidGreet: GreetFunction = (name: number) => `Hello, ${name}`; // Kesalahan: Parameter 'name' tidak dapat diassign
Dalam contoh ini, kita menggunakan typeof greet
untuk membuat tipe GreetFunction
yang cocok dengan tanda tangan fungsi greet
kita. Ini memastikan bahwa setiap fungsi yang diassign ke variabel tipe GreetFunction
memiliki parameter dan tipe kembalian yang sama.
Contoh 4: Tipe Enum
typeof
bisa sangat berguna saat bekerja dengan enum:
enum Color {
Red,
Green,
Blue
}
type ColorType = typeof Color;
// Penggunaan
const colorUtils: ColorType = {
Red: 0,
Green: 1,
Blue: 2
};
const invalidColorUtils: ColorType = {
Red: 0,
Green: 1,
Yellow: 2 // Kesalahan: 'Yellow' tidak ada dalam tipe 'typeof Color'
};
Di sini, typeof Color
memberikan kita tipe yang mewakili struktur enum Color
. Ini bisa berguna untuk membuat objek yang membutuhkan bentuk yang mirip dengan enum.
Contoh 5: Kombinasi dengan keyof
Operator typeof
bermain lancar dengan fitur lain TypeScript. Mari kita lihat bagaimana itu bekerja dengan keyof
:
const dimensions = {
width: 100,
height: 200
};
type DimensionKeys = keyof typeof dimensions;
// Penggunaan
function getDimension(key: DimensionKeys): number {
return dimensions[key];
}
console.log(getDimension("width")); // Valid
console.log(getDimension("depth")); // Kesalahan: Argumen tipe '"depth"' tidak dapat diassign ke parameter tipe 'keyof typeof dimensions'
Dalam contoh ini, kita mengkombinasikan keyof
dan typeof
untuk membuat tipe yang mewakili kunci objek dimensions
. Ini memungkinkan kita untuk membuat fungsi yang hanya dapat menerima kunci valid dari objek.
Tabel Metode
Berikut adalah tabel yang menggabungkan titik kunci tentang operator typeof
:
Metode | Deskripsi | Contoh |
---|---|---|
typeof variable |
Ekstrak tipe variabel | type T = typeof myVariable; |
typeof object |
Buat tipe yang cocok dengan struktur objek | type ObjectType = typeof myObject; |
typeof function |
Buat tipe yang cocok dengan tanda tangan fungsi | type FuncType = typeof myFunction; |
typeof enum |
Buat tipe yang mewakili struktur enum | type EnumType = typeof MyEnum; |
keyof typeof object |
Buat union type dari kunci objek | type Keys = keyof typeof myObject; |
Kesimpulan
Dan di sana Anda punya nya, teman-teman! Kita telah mengeksplorasi operator typeof
di TypeScript, dari sintaks dasarnya hingga kasus penggunaan yang lebih lanjut. Ingat, typeof
adalah seperti pisau瑞士 Army di dalam kotak alat TypeScript Anda – itu universal, kuat, dan dapat membuat kode Anda lebih kokoh dan fleksibel.
Sebagai Anda terus melanjutkan perjalanan TypeScript Anda, Anda akan menemukan lebih banyak situasi di mana typeof
bisa sangat berguna. Itu tentang latihan dan eksplorasi. Jadi, jangan takut untuk mencoba dan lihat apa yang Anda bisa buat dengan alat ini yang kuat.
Selamat coding, dan semoga tipe Anda selalu kuat dan kesalahan Anda sedikit!
Credits: Image by storyset