![]() |
暴走的茴香 · TypeScript中联合类型赋值null/ ...· 1 周前 · |
![]() |
慷慨大方的皮带 · vue3+ts:shims-vue.d.ts· 2 天前 · |
![]() |
俊秀的路灯 · python ...· 8 月前 · |
![]() |
傲视众生的抽屉 · C++中出现《E0144 "const ...· 8 月前 · |
![]() |
灰常酷的手套 · SQLServer分页获取数据的存储过程_5 ...· 1 年前 · |
![]() |
酷酷的牛腩 · jdbcconnectionexceptio ...· 1 年前 · |
我在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: [],
![]() |
慷慨大方的皮带 · vue3+ts:shims-vue.d.ts 2 天前 |