1

Here is MyClass:

export class MyClass {
    one: string;
    two: string;

    constructor(init?: Partial<MyClass>) {
        if (init) {
            Object.assign(this, init);
        } else {
            this.one = 'first';
            this.two = 'second';
        }
    }

    getOneAndTwo(): string {
        return `${this.one} and ${this.two}!`;
    }
}

Here are three ways to instantiate MyClass:

import { MyClass } from './models/my-class';

let mine = new MyClass();
console.log(mine.getOneAndTwo());

mine = new MyClass({
    one: 'One',
    two: 'Two'
});
console.log(mine.getOneAndTwo());

mine = {
    one: 'Three',
    two: 'Four'
} as MyClass;
console.log(mine.getOneAndTwo());

The last call to getOneAndTwo() will throw an error that starts off like this:

TypeError: mine.getOneAndTwo is not a function
    at Object.<anonymous>

I assume that the TypeScript compiler allows this to compile because it assumes I am treating a TypeScript class like a TypeScript interface. Is there any way I can throw a warning or an error to prevent this assumption from happening?

1 Answer 1

1

I don't think there is anything out of the box that would perform the checks you want. From the TS Handbook:

Type assertions

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. Usually this will happen when you know the type of some entity could be more specific than its current type.

Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

I suppose checks as to whether or not mine is of type MyClass could be done, but might not be the most practical of solutions IMO

let mine = new MyClass({
    one: 'One',
    two: 'Two'
});

console.log(mine instanceof MyClass); //true

mine = {
    one: 'Three',
    two: 'Four'
} as MyClass;

console.log(mine instanceof MyClass); // false
Sign up to request clarification or add additional context in comments.

Comments

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.