1

So, with the awesome type safety features delivered by TypeScript, I'm running into a new kind of problem. Say I want to pass strongly typed view models around. Is it better to type these with primitive properties or KO-wrapped properties? Is there some way of making a standard interface that would support both? As in

interface IPerson {
    FirstName: String;
}

class Person implements IPerson {
    FirstName: String;
}

class KOPerson implements IPerson {
    FirstName:  KnockoutObservableString;
}

Obviously, the above won't compile. Is there any way to accomplish some kind of polymorphism where either unwrapped or KO-wrapped versions of view models can be passed around through the same shared interfaces? Without reverting to "any" typing everywhere? I hate to bake Knockout-awareness into all my view model types. I hope this line of questioning makes sense!

1 Answer 1

2

I don't see any reason why you wouldn't want to bake the KO awareness into your view models? In case you decide to switch from Knockout to another MVX framework you'd probably need to rethink your view models anyway.

What I'd do is to write TypeScript interfaces for the parameters you'll return from the back end. In this way, your interface with the back end is clearly typed and defined. Should you want to switch to another framework, you could reuse this typing.

Sign up to request clarification or add additional context in comments.

2 Comments

Good thoughts. Yeah, I guess I wanted to keep the view models agnostic of whatever framework was using them (an advantage that is present in vanilla Javascript). I figure that if I'm already typing the view to KO (through bindings), it's preferable not to tie the view models to it as well. But, maybe there's no great way to do that! I'll bite the bullet for now and just make them KO-aware. Thanks!
If you would type your viewModels with raw types, you would also lose the benefit the Knockout types give you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.