Owner extends User {}
class Admin extends Owner {}
class BaseProcessor {
getRelatedOwner(owner: Owner): Owner {
return owner
}
}
class ChildProcessor extends BaseProcessor {
// User <-- Owner --> Admin
// input --> output
// input: User <+-- Owner --!> Admin // covariance
// output: User <!-- Owner --+> Admin // contravariance
// User <!-- Owner --> Admin // invariance
// input
// User -> more general type (super type) -> ok
// Admin -> more concrete type -> error
// output completely the other way round
// User -> error
// Admin -> ok
getRelatedOwner(owner: User): Admin {
declare var o: Admin // return is not compatible with the result -> use hack !
return o
}
}
// ======================
function logger(entity: { +name: ?string }) { // name: ?string -> works the same // solving -> +name: ?string -> property name is covariant !
console.log(entity.name) // flow have no idea how you are using field name here !
//entity.name = '123'
}
/*
function logger(entity: { -name: ?string }) { // -name: string -> contravariance !
//console.log(entity.name)
entity.name = '123'
}
*/
type Entity = {
name: string // name: string
}
const foo: Entity = {
name: 'Vasya'
}
logger(foo)
// =======================
type Ent = {
process: (x: string) => number,
}
const r: Ent = {
process(x: mixed) { // all is ok because process takes more general type
return 5
}
}
и что?
Обсуждают сегодня