所以我想找到一种方法来拥有嵌套对象的所有键。
我有一个在参数中采用类型的泛型类型。我的目标是获取给定类型的所有键。
在这种情况下,以下代码运行良好。但是当我开始使用嵌套对象时,情况就不同了。
type SimpleObjectType = {
a: string;
b: string;
};
// works well for a simple object
type MyGenericType<T extends object> = {
keys: Array<keyof T>;
};
const test: MyGenericType<SimpleObjectType> = {
keys: ['a'];
}
Run Code Online (Sandbox Code Playgroud)
这是我想要实现的目标,但它不起作用。
type NestedObjectType = {
a: string;
b: string;
nest: {
c: string;
};
otherNest: {
c: string;
};
};
type MyGenericType<T extends object> = {
keys: Array<keyof T>;
};
// won't works => Type 'string' is not assignable to type 'a' | …Run Code Online (Sandbox Code Playgroud) 我无法弄清楚如何将react-i18next 与typescript 4.1 一起使用。
根据文档,我应该能够执行以下操作:
const { t } = useTranslation();
return <h1>{t('title')}</h1>
Run Code Online (Sandbox Code Playgroud)
但是,该调用会t出错:
No overload matches this call: Argument of type 'string' is not assignable to parameter of type 'never'.
Run Code Online (Sandbox Code Playgroud)
有效的是使用:
useTranslation<string>()
或者
useTranslation('translation')
这两个条件似乎都是不必要的。
这似乎只适用于 typescript 4,好像我降级到 typescript 3 错误就会消失。
有没有办法在 TypeScript 4 中使用较短的内容useTranslation()?