typescript 只采用接口(interface)中定义的属性

标签 typescript casting

我是 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/

相关文章:

javascript - 单击后将选中的项目移至同一页面的其他选项卡

meteor - 我如何在 typescript 中导入 meteor 角色?

javascript - 类型错误 : Cannot read property 'match' of undefined 中的错误

c++ - 实现可以转换为 Stream<U> 的 Stream<T>,其中 U 是 T 的基数

typescript - 模块的所有接口(interface)和类型声明都应该放在一个文件中吗?

c# - 派生类的继承方式是否不同?

generics - Typescript 中的通用转换

python - Django ORM - 将原始值分配给 DecimalField

java - 为什么 '(int)(char)(byte)-2' 在 Java 中产生 65534?

javascript - 在 JavaScript 上将属性从字符串更新为对象而不发生突变