我是 Typescript 的初学者,我有一个案例,我将一个对象分配给另一个遵循我定义的接口(interface)的对象。问题在于接收对象获取了源对象的所有属性,甚至是那些未在接口(interface)中定义的属性,这会导致调用 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 中是否有一种优雅的方法来实现这一点?
最佳答案
您可以使用 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 类型在运行时会被剥离。
关于 typescript 只采用接口(interface)中定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65810493/