我无法正确实现泛型isEmpty(value),将提供的值的类型限制缩小到空的对应项。
使用案例:
function getCountryNameById(countries: LookupItem[] = [], countryId?: number): string | undefined {
if (isEmpty(countries) || !isNumber(countryId)) {
// within this branch I would like to get countries argument to be narrowed to empty array type.
// Same would apply for other function which can have argument type of object or string. Why ? -> to prevent someone to do some mad code hacks like accessing non existent value from empty array ( which would happen on runtime …Run Code Online (Sandbox Code Playgroud) 当 optional 和 required 属性通过交集合并时, required 获胜
type A = { who: string }
type B = { who?: string }
// $ExpectType {who:string}
type R = A & B
Run Code Online (Sandbox Code Playgroud)
这可能会导致运行时错误,例如,在处理函数中的默认参数模式时
type Params = {
who: string
greeting: string
}
const defaults: Params = {
greeting: 'Hello',
who: 'Johny 5',
}
function greeting(params: Partial<Params>){
// $ExpectType Params
const merged = {...defaults, ...params}
return `${merged.greeting.toUpperCase()} ${merged.who} !`
}
// @throws - TypeError: Cannot read property 'toUpperCase' of undefined
greeting({greeting:undefined, who: 'Chuck'}) …Run Code Online (Sandbox Code Playgroud) 我想从TS 3.1中的对象获取具有正确类型文字的正确元组类型:
interface Person {
name: string,
age: number
}
// $ExpectType ['name','age']
type ObjectKeysTuple = ToTuple<keyof Person>
Run Code Online (Sandbox Code Playgroud)
为什么?:
使用时获取正确的字符串文字元组 Object.keys(dictionary)
随着keyof工会的扩大,我无法找到解决方案,这('name' | 'age')[]肯定不是我们想要的。
type ObjectKeysTuple<T extends object> = [...Array<keyof T>]
type Test = ObjectKeysTuple<Person>
// no errors not good
const test: Test = ['age','name','name','name']
Run Code Online (Sandbox Code Playgroud)
有关: