打字稿中的通用对象类型 [英] Generic Object type in typescript

查看:40
本文介绍了打字稿中的通用对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在打字稿中有什么方法可以为变量分配一个通用对象类型.这就是我所说的通用对象类型"

In typescript is there any way to assign a variable a generic object type. Here's what I mean by 'generic Object type'

let myVariable: GenericObject = 1 // Should throw an error
                              = 'abc' // Should throw an error
                              = {} // OK
                              = {name: 'qwerty'} //OK

即它应该只允许将 javascript 对象分配给变量,而不允许将其他类型的数据(数字、字符串、布尔值)

i.e. It should only allow javascript objects to be assigned to the variable and no other type of data(number, string, boolean)

推荐答案

当然:

type GenericObject = { [key: string]: any };

let myVariable1: GenericObject = 1; // Type 'number' is not assignable to type '{ [key: string]: any; }'
let myVariable2: GenericObject = 'abc'; // Type 'string' is not assignable to type '{ [key: string]: any; }'
let myVariable3: GenericObject = {} // OK
let myVariable4: GenericObject = {name: 'qwerty'} //OK

(操场上的代码)

这篇关于打字稿中的通用对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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