How to reduce javascript object to only contain properties from interface

后端 未结 7 1386
迷失自我
迷失自我 2020-12-06 04:29

When using typescript a declared interface could look like this:

interface MyInterface {
  test: string;
}

And an implementation with extra

7条回答
  •  天命终不由人
    2020-12-06 04:43

    In a general way, how can you make the 'reduced' variable to only contain the properties declared in the 'MyInterface' interface.

    Since TypeScript is structural this means that anything that contains the relevant information is Type Compatible and therefore assignable.

    That said, TypeScript 1.6 will get a concept called freshness. This will make it easier to catch clear typos (note freshness only applies to object literals):

    // ERROR : `newText` does not exist on `MyInterface`
    var reduced: MyInterface = {test: "hello", newTest: "world"}; 
    

提交回复
热议问题