提问人:Snap 提问时间:12/25/2020 最后编辑:Snap 更新时间:12/25/2020 访问量:263
TypeScript - 为什么要定义设置为编译时未知的已定义对象的静态属性?
TypeScript - Why is a static property that is set to a defined object not known at compile time to be defined?
问:
我正在尝试访问类的静态属性。当我尝试编译它时,我收到错误。为什么要定义设置为编译时未知的已定义对象的静态属性?Object is possibly 'undefined'
我有三个类,每个类都在自己的文件中定义:
目录内容.ts
export class DirectoryContents
{
public readonly directories: ReadonlyArray<string>;
public readonly files: ReadonlyArray<string>;
public constructor(directories: ReadonlyArray<string>, files: ReadonlyArray<string>)
{
this.directories = directories;
this.files = files;
}
}
RootDirStructure.ts(根目录结构.ts)
01| import {DirectoryContents} from "./DirectoryContents";
02| import ReadOnlyDict = NodeJS.ReadOnlyDict;
03|
04| export class RootDirStructure
05| {
06| private static readonly REQUIRED_NPM_DIRECTORIES: ReadonlyArray<string> =
07| ["node_modules"];
08|
09| private static readonly REQUIRED_NPM_FILES: ReadonlyArray<string> =
10| ["package.json", "package-lock.json"];
11|
12| // RootDirStructure.required.npm set to defined object
13| public static readonly required: ReadOnlyDict<DirectoryContents> =
14| {
15| npm: new DirectoryContents(RootDirStructure.REQUIRED_NPM_DIRECTORIES, RootDirStructure.REQUIRED_NPM_FILES)
16| }
17| }
索引.ts
01| import {RootDirStructure} from "./RootDirStructure";
02|
03| class Index
04| {
05| // The following reference to RootDirStructure.required.npm causes error
06| const requiredNPMDirectories: ReadonlyArray<string> = RootDirStructure.required.npm.directories;
07| }
在第 15 行,其静态属性被设置为定义的对象。然而,当在 的第 6 行引用对象时,它会创建错误。RootDirStructure.ts
Index.ts
Object is possibly 'undefined'
既然它是一个静态属性,其值应该在编译时已知,为什么要定义一个在编译时不知道的已定义对象的静态属性?
答:
0赞
Snap
12/25/2020
#1
我能够通过重写来修复它。RootDirStructure.ts
我将静态属性设置为静态内部类,而不是具有类型的属性,因此现在如下所示:RootDirStructure.required
ReadOnlyDict<DirectoryContents>
RootDirStructure.ts
import {DirectoryContents} from "./DirectoryContents";
export class RootDirStructure
{
private static readonly REQUIRED_NPM_DIRECTORIES: ReadonlyArray<string> =
["node_modules"];
private static readonly REQUIRED_NPM_FILES: ReadonlyArray<string> =
["package.json", "package-lock.json"];
// RootDirStructure.required.npm set to defined object
public static readonly required = class
{
public static readonly npm: DirectoryContents = new DirectoryContents(RootDirStructure.REQUIRED_NPM_DIRECTORIES, RootDirStructure.REQUIRED_NPM_FILES);
}
}
我仍然很感兴趣,想知道为什么我之前会收到错误。我更喜欢原始语法。
下一个:C - 未定义的引用
评论
public static readonly required = { npm: ... }
ReadOnlyDict
{ [key: string]: T }
npm
ReadOnlyDict
{ [key: string]: T }
DirectoryContents
npm