注意:对于下面所示的所有代码,TypeScript都是用tsc --strict调用的。
给定一个单例对象o
const o = {
foo: 1,
bar: 2,
baz: 3,
};
如果我有一个在编译时无法知道的字符串值(例如来自用户输入),我希望安全地使用该字符串来索引o。我不想向o添加索引签名,因为它既不是动态的,也不是可扩展的--它总是有这三个键。
如果我尝试简单地使用字符串来索引o
const input = prompt("Enter the key you'd like to access in `o`");
if (input) {
目标
我想编写一个单元测试,以便在运行时验证JavaScript对象是否符合TypeScript类型。我正在寻找一种方法来做到这一点,让我可以描述类型一次,然后,然后它为TypeScript编译时检查和JavaScript运行时检查。解决方案必须允许嵌套类结构。
代码
因为一个代码示例值1000字.看“??”问题的根源是:
目标单元测试
it('object literal and TypeScript class should be compatible, () => {
??? psudo-code on line below ???
const isCom
function multiply(num: number): number {
console.log(num * 10) // NaN
return num * 10
}
multiply("not-a-number") // result == NaN
如果我试图通过硬编码无效的参数类型来调用上面的函数,Typescript会报错。这是意料之中的。
当参数被动态传递时,我期望的是同样的事情。
const valueFromDifferentSource = "not-a-number"
multiply(valueFromDifferentSou
我在TypeScript 3.2.2和strict: true上。
我无法键入具有一组动态定义键的普通对象,但所有这些键都有一个有保证的非空值类型。
[TypeScript游乐场示例]()
// Will assume any property access has type T
interface Object<T> {
[key: string]: T;
}
// Will assume Object.values() could be undefined
interface Object<T> {
[key: string]: T | undef
在TypeScript中,我发现在处理解析后的JSON数据时,有时必须使用“any”类型。不幸的是,这使得忽略类型约束变得很容易,因为TypeScript允许从“any”类型进行隐式转换。
var obj = JSON.parse('{ "num": "this is a string", "str": 3 }');
var num: number = obj.num; // num = "this is a string"!
var str: string = obj.str; // str = 3!
我正
当创建一个新的并在app.js中打开默认的VSCode文件时,这一行;
const App: () => React$Node = () => {
返回
Type annotations can only be used in TypeScript files.
作为一个VSCode问题。
我是否应该将类型记录安装在中,或者这是VSCode之类的其他问题?当然,本机没有发布他们的默认app.js文件时出现了错误。
这是问题的内容。
{
"resource": "/d:/App/sw_lbi_app/App.js",
"owne
JSX工厂:
function h(type: string, _props, ..._children): HTMLElement {
return document.createElement(type); // breakpoint here is hit
}
tsconfig.json:
"jsx": "react",
"jsxFactory": "h"
在.tsx文件中的用法:
const element = <div></div>; // = any
TypeScript似乎没有推断出J
在ActionScript中,可以使用在运行时检查类型
var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite); // true
trace(mySprite is DisplayObject);// true
trace(mySprite is IEventDispatcher); // true
是否可以检测变量(扩展或)是否是TypeScript的某个类或接口?
我在语言规范中找不到任何关于它的东西。当使用类/接口时,它应该在那里。
--
更新:抱歉,我更新了我的问题和代码,它缺少索引器-关键元素。
我有一个TypeScript类:
export class TestClass {
something: string = "";
[index: string]: any;
}
索引器是这样的,所以我可以动态地从/分配给现有的类成员。例如测试=“嗨!”;
但是,当我在另一个TS类中导入这个& use时,我可以这样做:
var test: TestClass = new TestClass();
test.aPropertyNotInTheClass = "Why can I d
我正在使用带有DevExtreme UI框架的Angular 11 (11.2.14)。Typescript版本是4.0.7。我已经启用了strictTemplates,现在我在生产环境中编译时得到以下错误:
Error: src/app/views/product/product.component.html:11:45 - error TS2322: Type 'string | number | Date' is not assignable to type 'Date'.
Type 'string' is not assignable
我想要Object.assign到一个已知类型的对象,一组应该属于同一类型的对象文本中的属性。在TypeScript中,是否有更清晰的方法可以做到这一点,而不像本中所建议的那样,实际上调用标识函数,或者创建单独的变量?
type Person = {
first?: string;
last?: string;
}
// Overkill, actually generates code to call a function
function check<T>(value: T): T { return value; }
const dude: Person = {