打字稿仅采用接口中定义的属性

时间:2021-01-20 13:27:59

标签: typescript casting

我是 Typescript 的初学者,我有一个案例,我将一个对象分配给另一个遵循我定义的接口的对象。问题是接收对象获取了源对象的所有属性,即使是那些没有在接口中定义的属性,这会导致调用 API 时出现问题。我用以下示例对其进行了简化:

interface MyInterface {
  x: string;
  y: number;
}

const sourceObject = {x: 'name', y: 35, z: false};
const receivingObject: MyInterface = sourceObject;

console.log(receivingObject); // {x: "name", y: 35, z: false}

我也试过如下使用强制转换:

const receivingObject: MyInterface = sourceObject as MyInterface;

然后我不得不通过从源对象中删除不需要的属性来解决,但我想知道在 Typescript 中是否有一种优雅的方法来实现这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用 io-ts Exact Types

import * as t from 'io-ts'
import { getOrElseW } from "fp-ts/Either";

const MyInterface = t.type({
    x: t.string,
    y: t.number
})
type MyInterfaceType = t.TypeOf<typeof MyInterface>

const sourceObject = {x: 'name', y: 35, z: false};
const getOrNull = getOrElseW(() => null)

const receivingObject: MyInterfaceType | null = 
    getOrNull(t.exact(MyInterface).decode(sourceObject));

console.log(receivingObject) // { x: 'name', y: 35 }

如果没有库或额外的 javascript 代码,你就无法做到这一点,因为 typescript 类型在运行时会被剥离。