Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:
export function forceCast<T>(input: any): T {
// ... do runtime checks here
// @ts-ignore <-- forces TS compiler to compile this as-is
return input;
}
Then you can use it to force cast objects to a certain type:
import { forceCast } from './forceCast';
const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);
Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts
interface files into JSON schemas and using ajv
to validate in runtime.