|
|
深沉的烈马 · TypeScript: ...· 3 月前 · |
|
|
还单身的镜子 · Announcing TypeScript ...· 3 周前 · |
|
|
犯傻的水桶 · findFirst with ...· 2 周前 · |
|
|
酒量小的针织衫 · 【Python数据处理】pandas.Dat ...· 2 年前 · |
|
|
热心肠的钱包 · python中如何对复杂的json数据快速查 ...· 2 年前 · |
|
|
高大的毛衣 · C 数据类型 | 菜鸟教程· 2 年前 · |
|
|
含蓄的电影票 · Java最准确的获取当前一周开始时间和结束时 ...· 3 年前 · |
我在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: [],
|
|
犯傻的水桶 · findFirst with `undefined` value shouldn't return data · Issue #5149 · prisma/prisma · GitHub 2 周前 |
|
|
高大的毛衣 · C 数据类型 | 菜鸟教程 2 年前 |