字符串变量值作为类型中的属性

时间:2017-12-06 07:13:56

标签: javascript typescript types typescript-typings

我尝试创建一个具有变量值的类型作为属性

例如:

AndroidRuntime: Calling main entry com.android.commands.pm.Pm
11-19 00:37:50.867  7887  7887 E Pm      : Error
11-19 00:37:50.867  7887  7887 E Pm      : java.lang.NullPointerException
11-19 00:37:50.867  7887  7887 E Pm      :  at android.os.Parcel.readException(Parcel.java:1690)
11-19 00:37:50.867  7887  7887 E Pm      :  at android.os.Parcel.readException(Parcel.java:1637)
11-19 00:37:50.867  7887  7887 E Pm      :  at android.content.pm.IPackageInstaller$Stub$Proxy.createSession(IPackageInstaller.java:249)
11-19 00:37:50.867  7887  7887 E Pm      :  at com.android.commands.pm.Pm.doCreateSession(Pm.java:552)
11-19 00:37:50.867  7887  7887 E Pm      :  at com.android.commands.pm.Pm.runInstall(Pm.java:392)
11-19 00:37:50.867  7887  7887 E Pm      :  at com.android.commands.pm.Pm.run(Pm.java:142)
11-19 00:37:50.867  7887  7887 E Pm      :  at com.android.commands.pm.Pm.main(Pm.java:99)
11-19 00:37:50.867  7887  7887 E Pm      :  at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
11-19 00:37:50.867  7887  7887 E Pm      :  at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:277)
11-19 00:37:50.869  7887  7887 I art     : System.exit called, status: 1

我希望我能做到:

const myProp: string = 'my prop';
type Foo ={ 
    [myProp]: string
};

但得到错误:

  

[ts]类型文字中的计算属性名称必须直接引用   一个内置的符号。

2 个答案:

答案 0 :(得分:2)

如果要声明一个与字符串常量具有相同属性名称的类型,可以使用以下语法(查找类型语法)

const myProp = 'my prop';
type Foo = {
    [P in typeof myProp]: string
};
const test: Foo = {
    [myProp]: myProp
}

如果您想拥有其中几个键,可以使用联合类型:

const myProp = 'my prop';
const otherProp = "otherProp"
type Foo = {
    [P in (typeof myProp | typeof otherProp)]: string
};
const test: Foo = {
    [myProp]: myProp,
    [otherProp]: otherProp
}

typescript默认库实际上提供了一个类似于上述查找类型声明的类型,名为Record。使用此功能,您可以将类型写为:

type Foo2 = Record<typeof myProp, string>;

答案 1 :(得分:1)

下一版本的Typescript发布后,您就可以执行此操作。

feature已在typescript @ next中提供。如果您愿意,可以使用以下方式安装:
npm install typescript@next --save-dev

同时你可以使用@Titian Cernicova-Dragomir提供的方法

相关问题