Last active
December 17, 2019 01:00
-
-
Save fvilante/62e1644d3fd3b7b87002abf69f1f3d70 to your computer and use it in GitHub Desktop.
Typescript generics and subtypem
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
// Code used to answer bellow stackoverflow question: | |
// https://stackoverflow.com/a/59363875/8233039 | |
// super class | |
type _Super<T> = { | |
readonly prop1: `bar` | |
readonly propT: T | |
} | |
const _super: _Super<string> = { | |
prop1: `bar`, | |
propT: `` | |
} | |
// sub class | |
type _Sub<T> = { | |
readonly prop1: `bar` | |
readonly propT: T | |
readonly prop2: `thux` | |
} | |
const _sub:_Sub<number> = { | |
prop1: `bar`, | |
propT: 10, | |
prop2: `thux`, | |
} | |
type _DiffSub<T> = { | |
readonly prop1: `bar` | |
readonly propT: T | |
readonly prop3: `different` | |
} | |
const _diffSub: _DiffSub<string> = { | |
prop1: `bar`, | |
propT: ``, | |
prop3: `different`, | |
} | |
const _subAndDiffSub: _Sub<string> & _DiffSub<string> = { | |
prop1: 'bar', | |
propT: ``, | |
prop2: 'thux', | |
prop3: 'different', | |
} | |
const func = <A extends _Sub<any> & _DiffSub<any>>(a: A = _subAndDiffSub) => `foo` | |
// tslint:disable: no-null-keyword | |
const c0 = func(undefined) // ok | |
const c1 = func(null) // ok | |
const c2 = func(() => undefined) // ok | |
const c3 = func(10) // ok | |
const c4 = func(`hi`) // ok | |
const c4_1=func([1,2,3]) // ok | |
const c5 = func({}) //ok | |
const c6 = func(_super) // ok | |
const c7 = func(_sub) //ok | |
const c8 = func(_diffSub) //ok | |
const c9 = func(_subAndDiffSub) // ok |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment