0

If I define let bar: Bar; and assign bar = initialFooConfig;, is bar still of type Bar and an object, or is it now an object in literal notation?

As long as this assignment is possible vice versa (provided initialFooConfig not as const), what is the difference between initialFooConfig and initialBarConfig?

interface IFoo {
    code: number;
    name: string;
}

export const initialFooConfig: IFoo = {
    code: 12,
    name: "bar"
}


class Bar implements IFoo { 
    code: number;
    name: string;

    constructor(code: number, name: string) { 
        this.code = code;
        this.name = name;
    }
}

export const initialBarConfig = new Bar(12,"bar");
Hölderlin
  • 424
  • 1
  • 3
  • 16

1 Answers1

0

Typescript doesn't see any difference between IFoo and Bar, because they are exactly same

// all those are exactly the same
// they have absolutely no visible difference
// (exept the naming in hover)
type A = {a: number}
interface B {a: number}
class C {a: number = 0}

So you can assign them in every way possible.

In runtime their values will be whatever you see fit, you can use

let x: A | B | C = a{1}; // it's the same type anyways
if (x instanceof C) {} // if it's `C{a:1}`
if (Object.getPrototypeOf(x) === Object.prototype) {} // if it's `{a:1}`

to find if it's an object of class instance

If you want to not be able to assignable object to class, use

declare class IPrivate {
  #private;
}
const Private = Object as any as typeof IPrivate;

type A = {a: number}
interface B {a: number}
class C extends Private {a: number = 0}

let a: A = {a: 0}
let c: C = {a: 1}
//  ~ Property '#private' is missing in type 'A' but required in type 'C'.(2741)
Dimava
  • 7,654
  • 1
  • 9
  • 24
  • The question is about object instances, not about types. – Wiktor Zychla Aug 04 '23 at 12:53
  • @Dimava IMO this implies C is equal B no matter how constructor look like, and if `class C {a: number; constructor(a:number){this.a=a}}` equal B and `class C {a: number; constructor(b:B){this.a=b.a}}` equals B, then they are equal, they are? – Hölderlin Aug 04 '23 at 13:39
  • @Hölderlin yes, `C`(the instance) will be the same no matter the constructor or static methods and props. `typeof C`(the constructor) will be different. – Dimava Aug 04 '23 at 22:23
  • @Hölderlin updated answer – Dimava Aug 04 '23 at 22:31