我试图在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]后面的
假设我有一个映射到数据库表的类型,其中键是列名:
interface MyTable {
foo: string;
bar: number;
}
然后,我有另一个类型,它从表单字段映射到表行。
interface MyTableMap<T> {
columnName: keyof T;
formFieldName: string;
value: any;
}
// I want this to generate an error because 12345 is not a string based on the column name of "foo
我这样定义一个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
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 KeysOfUnion<T> = T extends infer P ? keyof P : never
// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
这让我很困惑:这里推断的是什么?我创建了一个心理模型,使用infer关键字类似于JS中的析构--当然,这种并行并不完美,但它确实帮助了我很多。
但是我看不到这里的任何上下文:T extends infer P?我在推断什么?P与T的关系是什么?
在TS操场上测试代码片段之后,我猜想这与将具有构造函数的类型与没有构造函数的类型分离有关。
ty
我如何才能做到这一点?
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 (我使用了版本4.13)中,当我从类继承时,父类的static方法中的this似乎是指继承类:
class Parent{
static ID = 0
public id: number
static create(){
return new this(this.ID)
}
constructor(id: number){
this.id = id
}
}
class Child extends Parent{
static ID = 1
}
let child = Chil