Skip to content

Instantly share code, notes, and snippets.

@fvilante
Created January 21, 2020 18:13
Show Gist options
  • Save fvilante/22715913a314557fa8e93d4eb7a92c11 to your computer and use it in GitHub Desktop.
Save fvilante/22715913a314557fa8e93d4eb7a92c11 to your computer and use it in GitHub Desktop.
Draft pseudo-type and message
// ===== PseudoType ==========
export type PseudoType<A> = {
readonly kind: 'PseudoType'
readonly __UNSAFE__TYPE: A //ATTENTION: type trick (at run-time is undefined, but at static-time is A)
}
export const PseudoType = <A>():PseudoType<A> => ({kind: 'PseudoType', __UNSAFE__TYPE: undefined as unknown as A})
//
const Test02 = () => {
type MyA = {
readonly prop1: string,
readonly prop2: number
}
const MyA = PseudoType<MyA>()
}
// ===== TypeKey ========
type TypeKey<A, K extends keyof A> = {
readonly kind: 'TypeKey'
readonly pseudoType: PseudoType<A>
readonly keyof: K
}
const TypeKey = <A>() => <K extends keyof A>(keyA: K): TypeKey<A,K> => ({
kind: 'TypeKey',
pseudoType: PseudoType<A>(),
keyof: keyA,
})
//
const Test01 = () => {
type MyA = {
readonly prop1: string,
readonly prop2: number
}
const MyA = TypeKey<MyA>()
const a = MyA('prop1')
}
// ====== Message =============
type Message<A, K extends keyof A, P extends A[K]> = {
readonly kind: 'Message'
readonly pseudoType: PseudoType<A>
readonly name: K
readonly payload: P
}
const Message = <A, K extends Exclude<keyof A, 'kind'>>(p: PseudoType<A>, name: K, payload: A[K]): Message<A, K, A[K]> =>
({ kind: 'Message', pseudoType: p, name, payload})
const Test03 = () => {
type CMPP00LG = {
readonly kind: 'CMPP00LG'
readonly prop1: string,
readonly prop2: string
}
type CMPP00AF = {
readonly kind: 'CMPP00AF'
readonly prop1: string,
readonly prop2: string,
readonly prop3: string,
}
const CMPP00LG = PseudoType<CMPP00LG>()
const CMPP00AF = PseudoType<CMPP00AF>()
const m1 = Message(CMPP00LG, 'prop1', '')
const m2 = Message(CMPP00LG, 'prop2', '')
const m3 = Message(CMPP00AF, 'prop1', '')
const m4 = Message(CMPP00AF, 'prop2', '')
const m5 = Message(CMPP00AF, 'prop3', '')
const m6 = Message(CMPP00AF, 'prop2', '')
const f = <A extends CMPP00LG>(d:A) => undefined
const userLG: CMPP00LG = { kind: 'CMPP00LG', prop1: '', prop2: '' }
const userAF: CMPP00AF = { kind: 'CMPP00AF', prop1: '', prop2: '', prop3: '' }
const t0 = f(userLG)
const t1 = f(userAF)
type Target = {
readonly prop1: Message<CMPP00LG, 'prop1', string>
readonly prop2: Message<CMPP00LG, 'prop2', string>
readonly prop3: Message<CMPP00LG, 'prop2', string>
}
// tslint:disable-next-line: no-expression-statement
type Juca = ReturnType<typeof CMPP00LG>
}
// GENERIC
type ExternalMatcher<A, B> = {
readonly [KB in keyof B]: readonly [keyof A, (_:) => B[KB]]
}
// SPECIFIC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment