0
const foo = { bar: 1 }
foo.a = 2
foo.b = '3'
foo.c = { c: { d: 1 } }

这种往对象里加属性的写法的用ts怎么实现

const foo = { bar: '1,2,3' }
foo.bar = <string[]>foo.bar.split(',')

这种强制转换可以做到吗

3个回答

0

const foo as any = { bar: 1 }

0

const foo:any = {a:”111111”}

不过这样就跳过类型检查了

0

JS

const foo = { bar: 1 };
foo.a = 2;
foo.b = '3';
foo.c = { c: { d: 1 } };

转为TS

type Foo = { [key: string]: string | number | Foo };

const foo: Foo = { bar: 1 };
foo.a = 2;
foo.b = '3';
foo.c = { c: { d: 1 } };

撰写答案