【发布时间】:2018-07-09 05:39:47
【问题描述】:
我在纠结 JS/JSON.stringify 的这个特性:
const v = [];
v.foo = 5;
v.start = true;
console.log(JSON.stringify({value: v}));
你会在控制台中得到这个:
{"value":[]}
所以我想创建的类型是一个对象而不是一个数组:
export const acceptsObjectsButNotArrays = function(v: MyType){
v[marker] = true;
console.log(JSON.stringify({value:v});
}
使用 TS,是否有我可以用于 MyType 的定义,可以确保它是对象而不是数组?
export interface ObjectButNotArray extends Object {
[key:string]: any
}
它需要有一个索引签名,就像上面一样,所以我可以给它添加任意属性。
我能想到的最接近的事情是:
export type ObjectButNotArray = object & !Array<any>
虽然那个语法是假的。
【问题讨论】:
标签: typescript typescript2.0 tsc