|
|
儒雅的太阳 · ChatGPT in finance: ...· 1 年前 · |
|
|
潇洒的煎鸡蛋 · 层次结构数据 (SQL Server) - ...· 2 年前 · |
|
|
爱搭讪的蚂蚁 · C# 之 static的用法详解 - 知乎· 2 年前 · |
|
|
侠义非凡的炒面 · 记一次 Maven ...· 2 年前 · |
|
|
光明磊落的登山鞋 · 将 IDENTITY 转换为数据类型 ...· 2 年前 · |
我在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: [],
|
|
爱搭讪的蚂蚁 · C# 之 static的用法详解 - 知乎 2 年前 |