以下代码会导致错误,因为根据TypeScript,类型Pick<Test<T>, Exclude<keyof T, "someKey">>不能赋值给T。当我推断这种类型时,它应该被赋值给T,有没有办法让TypeScript同意我的观点?或者这只是突破了TypeScript中泛型类型的界限,因为不是动态类型的变体可以正确编译。 type Test<T = {}> = T & {
someKey: string
};
function extract<T>(props: Test<T>): T
我们的TypeScript代码库中有“安全”字符串:
button.on('click', () => {}); // mistyping 'click' is an error
但也有不安全的字符串:
_.omit(obj, 'a'); // no error if I mistype 'a'
有没有办法列出这样的字符串?我猜TypeScript对此有所了解,但我不确定是否能从中挖掘出来。
我一直在研究并尝试将现有项目(从Node.js)转换为TypeScript。
对于上下文,我使用的是http-status包()
我试图将变量传递到它们的默认导出中,但是它得到了一个错误:
import status = require("http-status");
status.OK; // this works
status["OK"] // this also works
let str = "OK";
status[str]; // error
错误:
元素隐式具有'any‘类型,因为类型'string’的表达式不能
我有一个使用keyof特性的简单函数: interface B {
name: string;
age: number;
}
function test(key: keyof B) {}
const c = {
age: 'age'
}
test(c.age); 上面代码的问题是typescript抛出了一个错误,即type string is not assignable to keyof B。 那么,如果keyof特性不能与对象键值一起使用,那么它还有什么意义呢?我不想添加as keyof B。
我已经编码TypeScript几年了。我已经看到了它的发展,并在每一个版本中都做了很多改进。然而,所有这些静态类型的完美都会随着类型的转换而分崩离析。
尽管在TypeScript中进行了大量的编码,但我仍然不明白如何避免在生成对象转换的函数中转换。
如下面的示例所示:我希望以一个对象作为输入,并将该对象的转换副本作为输出返回。
function stringifyProperties<T>(obj: T): { [P in keyof T]: string } {
let stringified: { [P in keyof T]: string } = {} as any
为什么这段代码不能编译?
type A = { n: number }
type B = { s: string }
type Thing = {
a: A
b: B
}
function update(obj: Thing, path: keyof Thing) {
obj[path] = obj[path]
}
我希望赋值的两端都有A | B类型,但TypeScript编译器失败了,出现以下错误:
error TS2322: Type 'A | B' is not assignable to type 'A & B'.
Type
我目前正在从事一个web项目,该项目大量地利用了国际化(i18n),并且我很难弄清楚如何确保所有语言共享完全相同的密钥。
下面是一个src/lang/en.ts文件的简单示例:
export default {
title: "My Website Project",
description: "This is an example of a file which contains phrases and their keys",
hello: "Hello!",
};
下面是一个简单的src/lang/id.ts文件示例:
expo
是否可以使用typescript条件检查确切的any类型? type IsAny<T> = T extends any ? true : never
type A = IsAny<any> // true
type B = IsAny<number> // never
type C = IsAny<unknown> // never
type D = IsAny<never> // never
我试图让TypeScript理解我的精简的结果,并为我的工厂方法的结果保留原始的类型。现在我得到了一个Element implicitly has an 'any' type because type '{ fetchSomething: (i: number) => (query: SomethingQuery) => Promise<{ [s: string]: string; }[]>; ...' has no index signature.
我的generateApiMethods函数的结果与apiFactories对象文本的结
我这样定义一个AbstractModel:
export interface AbstractModel {
[key: string]: any
}
然后我将类型声明为Keys
export type Keys = keyof AbstractModel;
我希望任何具有Keys类型的内容都会被统一地解释为一个字符串,例如:
const test: Keys;
test.toLowercase(); // Error: Property 'toLowerCase' does not exist on type 'string | number'. Pro
请考虑以下代码:
const obj = {
a: 1,
b: 2
}
let possibleKey: string = 'a'
if (possibleKey in obj) console.log(obj[possibleKey])
当possibleKey in obj为真时,我们知道possibleKey有keyof typeof obj类型,对吗?为什么TypeScript类型系统不能检测到这一点,并将string缩小到该类型?相反,它说:
Element implicitly has an 'any' type because