interface A {
name?: string
age: number
}
var a: A = {
name: '',
age: 23
}
var result:A = (Object.keys(a) as Array<keyof A>).reduce((prev, key) => {
if (a[key] || a[key] === 0) {
prev[key] = a[key] // this reported a error about `Type 'undefined' is not assig
我如何才能做到这一点?
type Fruit = "apple" | 'banana' | 'coconut'
type FruitCollection = { [f in Fruit]?: number }
const validFruitCollection: FruitCollection = { apple: 1, coconut: 2 }
const emptyCollectionShouldNotPass: FruitCollection = {} // I don't want typescript to let t
我试图在Typescript中更深入地理解高级类型,其中一种类型是NonFunctionPropertyNames,它只提取给定对象的一个属性。 type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T]; 我可以理解花括号'{ [K in keyof T]: T[K] extends Function ? never : K }'中的第一部分,我们声明了一个对象,并排除了扩展函数的属性。让我困惑的是花括号[keyof T]后面的
我有一个对象,其中一个属性的类型依赖于另一个属性的类型。例如: // The item types
enum ItemType { APPLE, SANDWICH }
// Map of a given item type to it's options
type ItemTypeToOptionsMap = {
[ItemType.APPLE]: { ripeness: string }
[ItemType.SANDWICH: { filling: string }
}
// The item type in question
type Item<T extend
如果我键入以下内容:
interface A {
x: number
}
interface B {
y: number
}
type Z = A | B;
// here it allows me to create a variable of type Z with both members of type A and B.
let z: Z = {
x: 5,
y: 6,
}
我无法确保Z类型的对象包含A的所有成员,但不包含B的成员(或相反的)。有可能用TypeScript吗?经过大量的研究,我倾向于“不”的答案,但我不确定。
是否可以创建一个TypeScript类型保护函数来确定给定键是否位于与key in obj类似的给定(泛型)对象- very中,但作为函数类型保护(由于与此问题无关的原因而需要)。
例如,如下所示:
export function has<T extends { [index: string]: any; [index: number]: any }>(
obj: T,
property: string | symbol | number
): property is keyof T {
return Object.prototype.hasOwnProperty.ca
我无法构建我的ionic 2应用程序。Serving在更改文件后工作。
在ionic serve上,我得到以下错误消息:
[07:36:10] ionic-app-scripts 1.0.0
[07:36:10] watch started ...
[07:36:10] build dev started ...
[07:36:10] clean started ...
[07:36:10] clean finished in 1 ms
[07:36:10] copy started ...
[07:36:10] transpile started ...
[07:
为什么我不能仅仅根据成员x是字符串而不是数字的信息来区分这个联合呢?为什么我必须使用文本类型?
type A = { x: string ; y: string }
type B = { x: number ; y: number }
type C = A | B
function fn(p: C) {
if (typeof p.x === 'string') {
// Typescript is unable to infer p as A
// Typescript infer p.y as (string | number), why not ju
当我在angular2 (typescript)中使用aws-sdk时,我得到了以下错误
import * as AWS from 'aws-sdk';
AWS.config.credentials.get
[ts]
Property 'get' does not exist on type 'Credentials | CredentialsOptions'.
Property 'get' does not exist on type 'CredentialsO
不知道我想要什么typescript功能,但我想我需要一个通用的(如果那是一个typescript功能)。下面是我的要求。
下面是我到目前为止所知道的。
interface Event {
type: string;
}
type EventType<T extends Event> = T['type'];
type EventHandler<T extends Event> = (event:T): void;
// so far so good
type EventTypeAndHandlerTuple <T extends Event