代码之家  ›  专栏  ›  技术社区  ›  rasx

防止在类上使用TypeScript“interface style”字段初始值设定项

  •  1
  • rasx  · 技术社区  · 8 年前

    这是 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}!`;
        }
    }
    

    这里有三种实例化方法 类名 :

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

    最后一次呼叫 getOneAndTwo() 将抛出一个开始如下的错误:

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

    我假设TypeScript编译器允许进行编译,因为它假设我将TypeScript类视为TypeScript接口。有没有什么方法可以让我抛出警告或错误来阻止这种假设的发生?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Community Mohan Dere    5 年前

    我不认为有什么现成的东西可以执行你想要的检查。从 TS Handbook :

    类型断言

    有时,您最终会遇到比TypeScript更了解某个值的情况。当您知道某些实体的类型可能比其当前类型更具体时,通常会发生这种情况。

    类型断言是告诉编译器相信我,我知道我在做什么的一种方式。 类型断言类似于其他语言中的类型转换,但不执行数据的特殊检查或重构 . 它没有运行时影响,仅由编译器使用。 TypeScript假设程序员已经执行了所需的任何特殊检查。

    我想检查一下是否 mine 属于类型 MyClass 可以做到,但可能不是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
    
    推荐文章