我有一个如下定义的配置类型:
type Primitive = string | number | boolean;
type PrimitiveObject = {[key:string] : Primitive};
type Config = {
baseUrl: string,
timeout?: number,
params?: PrimitiveObject,
[key:string]: Primitive | PrimitiveObject | undefined
};
let conf1:Config = {baseUrl: "https://www.google.com"};
let conf2:Config = {baseUrl: "https://www.google.com", other: 0};
let conf3:Config = {baseUrl: "https://www.ggogle.com", params: {id: 1}};
let conf4:Config = {baseUrl: "https://www.google.com", other: 0, other2: {hello: "world"} };
现在我想将 ( baseUrl
, timeout
, params
)以外的属性限制为Primitive
, not Primitive | PrimitiveObject
。就像other2
inconf4
应该是一个错误。
我尝试了一些方法但失败了
type Config = {
baseUrl: string,
timeout?: number,
params?: PrimitiveObject
} | {
baseUrl: string
[key:string]: Primitive
};
let conf1:Config = {baseUrl: "https://www.google.com"};
let conf2:Config = {baseUrl: "https://www.google.com", other: 0};
let conf3:Config = {baseUrl: "https://www.ggogle.com", params: {id: 1}};
// other2 error, which is wanted
let conf4:Config = {baseUrl: "https://www.google.com", other: 0, other2: {hello: "world"} };
let conf5:Config = {other: 2}
// this is also valid, but params is not a PrimitiveObject, I wan't it throw error too
let conf6:Config = {baseUrl: "https://www.google.com", params: 1}
我是 TypeScript 的新手,有什么建议吗?
你可以试试这个方法:
type Config = {
baseUrl: string,
timeout?: number,
params?: PrimitiveObject
} | {
baseUrl: string
[key:string]: Primitive | undefined
params?: never
};
由于[email protected]
使用 setexactOptionalPropertyTypes
标志,您可以省略添加| undefined
可索引字段:
type Config = {
baseUrl: string,
timeout?: number,
params?: PrimitiveObject
} | {
baseUrl: string
[key:string]: Primitive
params?: never
};
由于 TS 游乐场中的错误,您必须exactOptionalPropertyTypes
在TS Config
弹出窗口中手动切换选项。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句