![](/img/trans.png)
[英]“A computed property name in an interface must directly refer to a built-in symbol”
[英]TypeScript A computed property name in a type literal must directly refer to a built-in symbol
ERROR in...component.ts (..,..):類型文字中的計算屬性名稱必須直接引用內置符號。 ...:找不到名稱“任何”。
我期待着一個 object,其中包含具有其他字符串的字符串,即:
{ abc: 'xyz' }
我做了什么:
foo: { [string]: string };
計算值上的識別名稱是必需的:
foo: { [bar: string]: string };
構建后我遇到了類似的問題。 我面臨的兩個問題是使用數字和/或枚舉值作為對象中的鍵。 只是為了幫助那些將來看到這一點的人。
export enum MyEnum {
one = 'stringOne',
two = 'stringTwo',
}
export const someMap = {
[ MyEnum.one ]: 'valueOne',
[ MyEnum.two ]: 'valueTwo',
};
這會將 someMap someMap
為一種看起來像......
export declare const someMap: {
[ MyEnum.one ]: string;
[ MyEnum.two ]: string;
};
請注意,鍵仍然是枚舉值而不是字符串,打字稿/角度不喜歡那樣,因為它期待類似......
export declare const someMap: {
[ x: string ]: string;
};
所以兩個可能的修復是......
someMap
分配顯式類型export interface ForceStringType {
[product: string]: string;
}
export const someMap: ForceStringType = {
[ MyEnum.one ]: 'valueOne',
[ MyEnum.two ]: 'valueTwo',
};
string
類型分配給someMap
鍵export const someMap: ForceStringType = {
[ MyEnum.one as string ]: 'valueOne',
[ MyEnum.two as string ]: 'valueTwo',
};
const CONSTANT_ONE = 123;
const CONSTANT_TWO = 321;
export const someMap = {
[ CONSTANT_ONE ]: 'valueOne',
[ CONSTANT_TWO ]: 'valueTwo',
};
這會將 someMap someMap
為一種看起來像......
export declare const someMap: {
[ CONSTANT_ONE ]: string;
[ CONSTANT_TWO ]: string;
};
請注意,鍵仍然是常量/數字值而不是字符串,打字稿/角度再次期待類似...
export declare const someMap: {
[ x: string ]: string;
};
所以一種可能的解決方法是......
someMap
每個鍵someMap
數字作為字符串export declare const someMap: {
[ `${CONSTANT_ONE}` ]: string;
[ `${CONSTANT_TWO}` ]: string;
};
注意:使用常量/數字作為鍵從
someMap
訪問值應該無關緊要,因為someMap
無論如何都會將其強制轉換為字符串,但可能最適合整體一致性。const valueOne: string = someMap[ CONSTANT_ONE ]; // vs const valueOne: string = someMap[ `${CONSTANT_ONE}` ];
我在 Vue 組件中遇到了這個問題,我的問題是我錯誤地綁定了 class 名稱:
<script lang="ts">
import { defineComponent } from '@vue/composition-api'
export default defineComponent({
props: {
className: String,
},
setup() {
const isModified = computed<boolean>(() => true)
return {
isModified,
}
<template>
<!-- BAD -->
<div
class="static-class"
:class="{ [className]: true, 'static-class--modified': isModified }]">
</div>
<!-- GOOD -->
<div
class="static-class"
:class="[className, { 'static-class--modified': isModified }]">
</div>
</template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.