首页 > 解决方案 > 打字稿确保类型包含子字符串

问题描述

我定义了一个SizeType并准备设置设备媒体查询类型检查。是否有可能不是string仅在 DeviceSize 上使用,而是必须包含子字符串min-width: ...,然后将其余字符串限制为size属性值?

type SizeType = 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
type Size = { [size in SizeType]: string };
type DeviceSize = { [size in SizeType]: string };

interface Theme {
    device: Required<Partial<DeviceSize>>;
}

const size: Size = {
    sm: '576px',
    md: '768px',
    lg: '1024px',
    xl: '1440px',
    xxl: '2560px',
};
const theme: Theme = {
    device: {
        sm: `(min-width: ${size.sm})`,
        md: `(min-width: ${size.md})`,
        lg: `(min-width: ${size.lg})`,
        xl: `(min-width: ${size.xl})`,
        xxl: `(min-width: ${size.xxl})`,
    },
}

使用当前设置,这将通过检查:

const theme: Theme = {
    device: {
        sm: `(min-width: ${size.sm})`,
        md: `(min-width: ${size.md})`,
        lg: `(min-width: 100)`,
        xl: `(min-width: 220px)`,
        xxl: `abc`,
    },
}

标签: typescripttypescript-typings

解决方案


当然,只需将您的字符串类型声明为具有您想要的模式的模板文字。

type DeviceSize = { [size in SizeType]: `(min-width: ${string})` };

现在应该会给您预期的错误:

const theme: Theme = {
    device: {
        sm: `(min-width: ${size.sm})`,
        md: `(min-width: ${size.md})`,
        lg: `(min-width: 100)`,
        xl: `(min-width: 220px)`,
        xxl: `abc`,
        // Type '"abc"' is not assignable to type
        //   '`(min-width: ${string})`'.(2322)
    },
}

操场

甚至:

`(min-width: ${number}px)`

如果你想验证它是一些px单位。


推荐阅读