限制打字稿类型定义

艾伦肖

我有一个如下定义的配置类型:

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就像other2inconf4应该是一个错误。

我尝试了一些方法但失败了

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 游乐场中的错误,您必须exactOptionalPropertyTypesTS Config弹出窗口中手动切换选项

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章