Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript:将可映射可索引类型和属性与接口中相同的值类型组合在一起_Typescript - Fatal编程技术网

Typescript:将可映射可索引类型和属性与接口中相同的值类型组合在一起

Typescript:将可映射可索引类型和属性与接口中相同的值类型组合在一起,typescript,Typescript,我想知道是否有一种干净的方法可以将可映射可索引类型与接口中相同值类型的属性组合在一起 这是一个有用的例子 export type SupportedLanguagesUnion = 'fr' | 'es'; export interface Translation { [word: string]: { default: string; [language in SupportedLanguagesUnion]?: string; } } 及

我想知道是否有一种干净的方法可以将可映射可索引类型与接口中相同值类型的属性组合在一起

这是一个有用的例子

export type SupportedLanguagesUnion = 'fr' | 'es';

export interface Translation {
    [word: string]: {
        default: string;
        [language in SupportedLanguagesUnion]?: string;
    }
}

此接口将确保没有不受支持的语言,但始终为默认值

不幸的是,此代码不是有效的typescript。我想问题在于默认值和具有相同值类型的语言之间的冲突

目前,我必须用不太安全的接口替换接口

export interface Translation {
    [word: string]: {
        default: string;
        [language: string]: string;
    }
}
这将接受以下代码

const translationDictionary: Translation = {
    hello: {
        default: "hello",
        foo: 'bar'
    }
};
我还可以在
SupportedLanguagesUnion
中添加
'default'
作为一个值,但随后它将成为可选的

是否有方法编写此接口以保留这两个检查?

您可以在交集(
&
)中使用映射类型(对于
SupportedLanguagesUnion
中的语言),该类型具有所需的额外属性:

export type SupportedLanguagesUnion = 'fr' | 'es';

export interface Translation {
    [word: string]: {
        default: string;
    } & {
        [language in SupportedLanguagesUnion]?: string;
    }
}

const translationDictionary: Translation = {
    hello: {
        default: 'hello',
        fr: 'bonjour',
        es: 'hola'
    }
};
export type SupportedLanguagesUnion = 'fr' | 'es';

export interface Translation {
    [word: string]: {
        default: string;
    } & {
        [language in SupportedLanguagesUnion]?: string;
    }
}

const translationDictionary: Translation = {
    hello: {
        default: 'hello',
        fr: 'bonjour',
        es: 'hola'
    }
};