【发布时间】: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