【问题标题】:TypeScript automatically `as const` my type which cause errorTypeScript 自动 `as const` 我的类型导致错误
【发布时间】:2019-11-04 14:49:37
【问题描述】:

请看下面的打字稿代码:

type Interpolation = null | undefined | boolean | number | string;

type DefaultTheme = {
    color: {
        primary: {
            active: string;
            default: string;
            hover: string;
            disabled: string;
            background: string;
        };
        secondary: {
            active: string;
            default: string;
            hover: string;
            disabled: string;
            background: string;
        };
    };
};

type Classes<K extends string> = {
    [className in K]: string;
};

type Theme = DefaultTheme & {
    [key: string]: any;
};

type DynamicStyle<K extends string> = (
    theme: Theme,
    deps: any[],
    classes: Classes<K>,
) => Interpolation;

type Style<K extends string> = string | DynamicStyle<K>;

type Styles<K extends string> = ReadonlyArray<readonly [K, Style<K>]>;

function makeStyles<K extends string>(styles: Styles<K>) {
    return styles;
}

makeStyles([
    [
        'tag',
        (theme, [a, b, c]) => {
            return '';
        },
    ],
    ['label', ''],
]);

这会导致错误

类型“字符串”不能分配给类型“标签”。

注意标签是'"tag"',我认为这是typescript as const我的类型。

我希望它是字符串,而不是 '"tag"'

有没有办法强制它成为一个字符串?

我认为打字稿会自动将其加宽为字符串,我不知道为什么这里的行为不同。

这是我的 tsconfig,我的 typescript 版本是 ^3.6.4

{
  "include": ["src", "types", "test"],
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "lib": ["dom", "esnext"],
    "importHelpers": true,
    "declaration": true,
    "sourceMap": true,
    "rootDir": "./",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "*": ["src/*", "node_modules/*"]
    },
    "jsx": "react",
    "esModuleInterop": true
  }
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我知道问题所在,因为这条线ReadonlyArray&lt;readonly [K, Style&lt;K&gt;]&gt;

    这似乎缩小了我的类型

    【讨论】:

      猜你喜欢
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 2020-10-18
      • 2021-02-10
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多