Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat(TypeScript): learn use ThisType<T>
  • Loading branch information
sebastiandotdev committed Apr 27, 2025
commit 68d301b4eb87f64c1637cad11fc9a99adec79743
3 changes: 3 additions & 0 deletions TypeScript/deno.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"lock": false,
"compilerOptions": {
"noImplicitThis": true
},
"imports": {
"@std/assert": "jsr:@std/assert"
}
Expand Down
45 changes: 45 additions & 0 deletions TypeScript/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,48 @@
/*************************************************************** ThisType<T> **************************************************************/
/**
* Ejemplo de uso de `ThisType<T>` en TypeScript para definir el tipo de `this` en métodos de un objeto.
*
* `ThisType<T>` es una utilidad de TypeScript que permite especificar explícitamente el tipo del contexto `this`
* dentro de los métodos de un objeto. Es útil en objetos literales, mixins, o frameworks como Vue.js, donde
* los métodos necesitan acceder a otras propiedades o métodos del mismo objeto.
*
* **Requisitos**:
* - La opción `--noImplicitThis` debe estar habilitada en `tsconfig.json` para evitar que `this` sea inferido como `any`.
*/
interface Counter {
/** El valor actual del contador */
amount: number;
/** Incrementa el valor del contador en 1 */
inc: () => void;
/** Decrementa el valor del contador en 1 */
dec: () => void;
}

/**
* Tipo que combina la interfaz `Counter` con `ThisType<Counter>` para tipar el contexto `this`.
*/
type CounterWithThis = Counter & ThisType<Counter>;

/**
* Implementación del objeto contador.
* Los métodos `inc` y `dec` usan `this` para modificar la propiedad `amount`.
* Gracias a `ThisType<Counter>`, TypeScript valida correctamente el acceso a `amount`.
*/
const counter: CounterWithThis = {
amount: 0,
inc() {
this.amount++;
},
dec() {
this.amount--;
},
};

counter.inc();
counter.dec();
console.log(counter.amount);
/***************************************************************** End ThisType<T> **************************************************************/

function main() {
/** Here we will write new things learned from TypeScript with basic examples */
}
Expand Down
Loading