JS追加属性值
- 用中括号包裹字符串
const data={};
data['name'] = "小明";
const class= 'class';
data[class] = "一年级";
- 直接为对象指明key属性
data.event = "打游戏";
第一种适用于方法封装
第二种适用于对象接收和定义
TS追加属性值
- 声明接口
export interface Response {
//查询对象
searchTarget: string;
//判断符
conjunction: string;
//查询参数
//equals greater less...
searchContent?: string;
//in between...
searchContents?: string[];
}
- 定义接收参数
const getSearchParam = (
searchTarget: string,
conjunction: string,
content: string | string[]
) => {
//这里需实现接口,并在接口中声明附加属性的参数
const searchParam: searchParam = {
searchTarget: searchTarget,
conjunction: conjunction,
};
if (typeof content == "object") searchParam["searchContents"] = content;
else searchParam["searchContent"] = content;
return searchParam;
};
注:当定义参数不符合接口中的参数或不实现接口时,会报TS7053: Element implicitly has an 'any' type because expression of type '"searchContents"' can't be used to index type '{ searchTarget: string; conjunction: string; }'. Property 'searchContents' does not exist on type '{ searchTarget: string; conjunction: string; }'.
,ts会找不到该属性的类型,这种写法不影响运行结果但不规范,不建议这么写