typescript 对象文字符号和通过构造函数定义的对象之间的交互

vuktfyat  于 2023-08-07  发布在  TypeScript
关注(0)|答案(1)|浏览(124)

如果我定义了let bar: Bar;并赋值给bar = initialFooConfig;,那么bar仍然是Bar类型和一个对象吗?或者它现在是一个文字表示法中的对象吗?
只要这种赋值是可能的,反之亦然(假设initialFooConfig不是const),initialFooConfiginitialBarConfig之间有什么区别?

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");

字符串

ars1skjm

ars1skjm1#

Typescript看不出IFoo和Bar之间有任何区别,因为它们完全相同。

// 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}

字符串
所以你可以用各种可能的方式分配它们。
在运行时,它们的值将是您认为合适的任何值,您可以使用

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}`


来判断它是否是类示例的对象
如果你不想让一个可赋值的对象被赋值给类,使用

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)

相关问题