我在TypeScript中有以下声明:
let foo = {
bar: []
};
foo.bar.push("Hello World!");
然而,VSCode一直抱怨说这是不允许的。
类型'string‘的参数不能分配给’从不‘. is (2345)类型的参数。
因此,我尝试将该类型定义为:
let foo = {
bar: Array<string>
};
但是,我得到了不允许方法推送的消息:
类型{ (arrayLength: number):string[];(...items: string[]):string[];new (arrayLength: number):string[];new (...items: string[]):string[];isArray( arg : any):arg是any[];只读原型: any[];from(arrayLike: ArrayLike):T[];from(arrayLike: ArrayLike<...>,mapfn:(v: T,k: number) => U,thisArg?:.‘..ts(2339)
我发现它起作用的唯一方法是将其定义如下:
let arr : Array<string> = [];
let foo = {
bar: arr
};
foo.bar.push('Hello World!')
为什么我不能定义对象本身内的类型呢?要将外部的类型提取到变量中似乎很麻烦。
发布于 2022-11-01 09:17:50
这应该是可行的:
let foo = {
bar: [] as string[]
};
您还可以使用一个类型化变量(imo)来执行此操作:
interface Foo {
bar: string[];
}
let foo: Foo = { bar: [] }
发布于 2022-11-01 09:34:21
你至少有几个选择:
您可以定义内联foo
的类型:
let foo: { bar: string[]; } = {
// ^^^^^^^^^^^^^^^^^^^^
bar: [],
};
foo.bar.push("Hello World!");
您甚至可以将其提取为可重用的类型:
type Foo = { bar: string[]; }; // <=== (You could also use `interface`)
let foo: Foo = {
bar: [],
};
foo.bar.push("Hello World!");
或者可以将空白数组上的类型断言作为由JC97显示使用(通常,最好避免类型断言,但对空数组的断言是一个合理的例外):
let foo = {
bar: [] as string[],
};
foo.bar.push("Hello World!");
https://stackoverflow.com/questions/74273713
复制相似问题