'A type-safe "as" for inline object construction in TypeScript
In TypeScript I often need an object to be of a certain type, as the inferred type doesn't produce the desired results -- this happens with type hierarchies with a base class, or when intermediates are used to store a value.
I've been using "as" for this, but it's not type-safe, for example, given:
interface SomeType {
some: integer
}
Then:
{ some: 123 } as SomeType // this passes
{ wrong: "abc" } as SomeType // but this also passes
If I assign to a variable I can get what I want:
const a : SomeType = { wrong: "abc" } // fails as desired
But in some cases it's inconvenient to use a variable. Is there an equivalent way to do the type-safe casting as an expression?
For my uses, I've added a simple function that seems to work:
export function safeAs<T>(value: T): T {
return value
}
Then:
safeAs<SomeType>({ some: 123 }) // this passes
safeAs<SomeType>({ wrong: "abc" }) // this fails, as wanted
But it feels that this is a fundamental need and I assume I'm missing some syntax that would already do this.
Note: I need this to work in TSX (react) files, which I know sometimes impinges on generic/type syntax.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
