Last active
March 27, 2024 08:18
-
-
Save alloy/cd945f6bdce9abb5c0e0ca57e1873137 to your computer and use it in GitHub Desktop.
Why does TypeScript inline the typeof type?
This file contains 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
const x = { | |
foo: "bar", | |
answer: 42 | |
} | |
type X = typeof x | |
export default { | |
get X(): X { | |
return x | |
} | |
} |
This file contains 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
declare const x: { | |
foo: string; | |
answer: number; | |
}; | |
declare type X = typeof x; | |
declare const _default: { | |
// Why inline the type here? | |
readonly X: { | |
foo: string; | |
answer: number; | |
}; | |
}; | |
export default _default; |
This file contains 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
declare const x: { | |
foo: string; | |
answer: number; | |
}; | |
declare type X = typeof x; | |
declare const _default: { | |
// Just use the named type reference | |
readonly X: X; | |
}; | |
export default _default; |
Ok, the solution looks to be to “brand” the type, making it a nominal type:
type UniqueBranding = { " Thou shalt ignore this here prop or risketh a runtime mad as a bag of ferrets."?: never };
type X = typeof x & UniqueBranding
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I thought I had a solution by capturing the type as an interface:
However, that unfortunately doesn’t work with unions: