我如何才能做到这一点?
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功能,但我想我需要一个通用的(如果那是一个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
我试图更深入地理解类型文本类型,我发现以下行为令人困惑:
interface Person {
name: string;
}
interface Lifespan {
birth: number;
death?: number;
}
let k: keyof (Person | Lifespan); //k is never
let test1: Person | Lifespan = { randomKey: 123 }; //I understand the error: Object literal may only specify known propert
当我在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
请考虑以下代码:
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
为什么TypeScript不缩小数组的类型?
function test(input: (string | number)[]): string[] {
// The type of .map(...) reports that it returns string[].
input = input.map(x => x.toString())
// Type error: Type '(string | number)[]' is not assignable to type 'string[]'.
return input
}
解决方法并
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
我有以下typescript代码:
type PossiblePromise<T> = T extends Promise<infer U>
? T | U
: T | Promise<T>;
type Z = PossiblePromise<boolean>;
const a = "a"
const f: () => Z = () => Promise.resolve(!!a);
将strictNullChecks设置为false。
结果类型Z是boolean | Promise<false>
为什么我不能仅仅根据成员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
如果我键入以下内容:
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