Last active
January 11, 2021 14:35
-
-
Save fhpriamo/ba0379713a48c0938f8e489f09ac8674 to your computer and use it in GitHub Desktop.
Demonstração de variança de tipos usando TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Covariança (aceita tipos iguais ou mais específicos - com mais propriedades) | |
// | |
interface A { | |
a: string; | |
} | |
interface B extends A { | |
b: string; | |
} | |
interface C extends B { | |
c: string; | |
} | |
const arg1 = { a: 'ah', b: 'bê', c: 'cê' }; // pode ser atribuído a variáveis que esperam os tipos A, B e C; | |
const arg2 = { a: 'ah', b: 'bê' }; // pode ser atribuído a variáveis que esperam os tipos A e B; | |
const arg3 = { a: 'ah' }; // pode ser atribuído a variáveis que esperam o tipo A; | |
export const b1: B = arg1; | |
export const b2: B = arg2; | |
// export const b3: B = arg3; // ERRO! (falta a propriedade 'b') | |
// | |
// Contravariança (aceita tipos iguais ou menos específicos - com menos propriedades) | |
// | |
function fn(cb: (a: number, b: number, c: number) => number): void { | |
cb(1, 2, 3); | |
} | |
function cb1(a: number) { | |
return a; | |
} | |
function cb2(a: number, b: number) { | |
return a + b; | |
} | |
function cb3(a: number, b: number, c: number) { | |
return a + b + c; | |
} | |
function cb4(a: number, b: number, c: number, d: number) { | |
return a + b + c + d; | |
} | |
fn(cb1); | |
fn(cb2); | |
fn(cb3); | |
// fn(cb4); // ERRO! (requer a propriedade d, que não é passada pela função que aceita o cb) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment