是否可以使用打字稿映射的类型来创建接口的非功能属性类型? [英] Is it possible to use typescript mapped types to make a type of non-function properties of an interface?

查看:105
本文介绍了是否可以使用打字稿映射的类型来创建接口的非功能属性类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在看Typescript的映射类型.是否可以创建一个包装另一个类型的接口,以从原始类型中删除功能?例如:

so I was looking at Typescript's mapped types. Would it be possible to create an interface that wraps another type that removes functions from the original type? For example:

interface Person{
name: string,
age: number,
speak(): void,
}

type Data<T> = ?

const dataPerson: Data<Person> ={
name: "John",
age: 20
//Speak removed because it is a function
};

谢谢!

推荐答案

这是来自打字稿文档(

This is from the typescript documentation (https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types) and works:

type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type Data<T> = Pick<T, NonFunctionPropertyNames<T>>;

谢谢大家!

这篇关于是否可以使用打字稿映射的类型来创建接口的非功能属性类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆